サーバーへのアップロード
ビューアーは変更を適用した結果をすぐに表示しますが、保存はアプリの役目です。この例では、編集した画像をサーバーに送り、結果をユーザーに知らせます。
この関数は画像をフォームのファイルとして送り、サーバーが受け付けなければ失敗します。
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}`)
}
}ビューアーは適用時にこれを呼び出し、ステータス行が結果を伝えます。
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: '請求書 42',
maxOutputSize: 3000,
})
pic.on('apply', async ({ blob, type }) => {
status.textContent = '保存中…'
try {
await upload(blob, type)
status.textContent = '保存しました'
}
catch {
status.textContent = '文書を保存できませんでした'
}
})補足
role="status"にすると、スクリーンリーダーがアップロードの結果を読み上げます。maxOutputSizeでファイルを小さく保てます。長辺 3000 ピクセルでも文書は読みやすいままです。- 適用のあとは履歴が空になるため、ユーザーは元の画像に戻せません。再試行ボタンを用意するなら、最後の
blobとtypeを保持して、もう一度uploadを呼び出してください。 - 白黒の文書ならサーバーには PNG が届き、それ以外は元画像が JPEG、PNG、WebP ならその形式です。PaperPic が形式をどう判断するか、別の形式の選び方は結果の保存を参照してください。