跳到正文

附加并扫描 ​

大多数接收文档的应用都会请用户提供一张照片,例如报销用的收据或签好字的表格。这个示例让用户拍照或选择文件,在 PaperPic 中编辑,再把结果发送到你的服务器。

upload 是上传到服务器中的函数,它发送图片,并在服务器不接受时失败。

html
<label>
  文档照片
  <input id="photo" type="file" accept="image/*" capture="environment" />
</label>
<div id="viewer" style="height: 480px"></div>
<p id="status" role="status"></p>
ts
import { PaperPic } from '@paperpic/core'
import '@paperpic/core/style.css'

const input = document.querySelector<HTMLInputElement>('#photo')!
const status = document.querySelector('#status')!

const pic = new PaperPic(document.querySelector<HTMLElement>('#viewer')!, {
  alt: '你附加的文档',
  maxOutputSize: 3000,
})

input.addEventListener('change', () => {
  const file = input.files?.[0]
  input.value = ''
  if (file) {
    status.textContent = ''
    pic.setOptions({ src: file })
  }
})

// 照片一显示就开始编辑
pic.on('load', () => pic.edit())

pic.on('error', ({ phase }) => {
  if (phase === 'load') {
    status.textContent = '这个文件不是浏览器能打开的图片'
  }
})

pic.on('apply', async ({ blob, type }) => {
  status.textContent = '正在发送…'
  try {
    await upload(blob, type)
    status.textContent = '已发送'
  }
  catch {
    status.textContent = '文档无法发送'
  }
})

说明 ​

  • capture="environment" 在手机上会打开后置摄像头,电脑会忽略它。不加它时,手机会同时提供相机和相册,适合用户已有的文档。
  • 每次选择后清空 input,用户就能再次选择同一张照片,例如在应用之后重新开始。
  • 照片加载后,查看器会进入编辑模式,用户可以直接使用矫正或清理。去掉 load 监听器即可先显示照片。
  • phase: 'load' 能把浏览器无法打开的文件(例如 Safari 之外的 HEIC 照片)与编辑失败区分开。加载图片列出了支持的格式。
  • 在用户应用修改、你的代码调用 upload 之前,照片一直留在浏览器中。PaperPic 不会自行发送任何内容。
  • maxOutputSize 让上传保持小巧。手机照片通常有 1200 万像素或更多,而文档在最长边 3000 像素时仍然清晰可读。

基于 MIT 许可证发布。