Skip to content

Send with a form ​

Some apps send documents with a plain form, such as an expense with its receipt, and have no code of their own to upload a file. This example keeps the photo in the file field of the form, and puts the edited image back in that field when the user applies the changes, so the form sends it as it would any file.

html
<form action="/api/expenses" method="post" enctype="multipart/form-data">
  <label>
    Amount
    <input name="amount" type="number" step="0.01" required />
  </label>
  <label>
    Receipt
    <input id="receipt" name="receipt" type="file" accept="image/*" required />
  </label>
  <div id="viewer" style="height: 480px"></div>
  <button type="submit">Send</button>
</form>
ts
import { PaperPic } from '@paperpic/core'
import '@paperpic/core/style.css'

const input = document.querySelector<HTMLInputElement>('#receipt')!
const pic = new PaperPic(document.querySelector<HTMLElement>('#viewer')!, {
  alt: 'The receipt you attached',
  maxOutputSize: 3000,
})

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

// The form sends the edited image in place of the photo
pic.on('apply', ({ blob, type }) => {
  const name = input.files?.[0]?.name.replace(/\.\w+$/, '') ?? 'receipt'
  const files = new DataTransfer()
  files.items.add(new File([blob], `${name}.${type.split('/')[1]}`, { type }))
  input.files = files.files
})

Notes ​

  • Apply puts the edited image in the file field with a DataTransfer, so the form sends it under the same name. Before any Apply, the form sends the photo as the user picked it.
  • Changing the files of the field from code does not fire its change event, so the viewer keeps the result on display.
  • The file keeps the name of the photo, with the extension of the result, such as receipt.png after Clean up in black and white.
  • The buttons of the viewer never submit the form.
  • maxOutputSize keeps the form light. Phone photos have 12 megapixels or more, and documents stay readable at 3000 pixels on the longest side.

Released under the MIT License.