Upload to a server
The viewer shows the result of Apply at once, but saving it is up to your app. This example sends the edited image to your server and tells the user how it went.
This function sends the image as a file in a form, and fails when the server does not accept it:
ts
async function upload(blob: Blob, type: string) {
const body = new FormData()
body.append('file', blob, `document.${type.split('/')[1]}`)
const response = await fetch('/api/documents/42', { method: 'PUT', body })
if (!response.ok) {
throw new Error(`The upload failed with status ${response.status}`)
}
}The viewer calls it on Apply, and a status line reports the result:
html
<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 status = document.querySelector('#status')!
const pic = new PaperPic(document.querySelector<HTMLElement>('#viewer')!, {
src: '/documents/42.jpg',
alt: 'Invoice 42',
maxOutputSize: 3000,
})
pic.on('apply', async ({ blob, type }) => {
status.textContent = 'Saving…'
try {
await upload(blob, type)
status.textContent = 'Saved'
}
catch {
status.textContent = 'The document could not be saved'
}
})Notes
role="status"makes screen readers announce the result of the upload.maxOutputSizekeeps the file small. Documents stay readable at 3000 pixels on the longest side.- After Apply, the history is empty, so the user cannot undo into the old image. To offer a retry button, keep the last
blobandtypeand calluploadagain. - The server receives PNG for a document in black and white, and otherwise the format of the source when it is JPEG, PNG or WebP. Read Saving the result to learn how PaperPic tells the format, and to choose another one.