Image uploads to S3
Uploading straight from the browser to object storage (S3, R2, GCS) keeps large files off your app server. Your backend only signs the upload.
ts
import { imageUpload, presignedUploader } from '@writeon/advanced'
import type { Editor } from '@writeon/core'
interface SignedUpload {
uploadUrl: string
publicUrl: string
}
// Your backend checks the type and size, signs a PUT for one
// object key and says where the file can be loaded from later.
async function signUpload(
file: File,
signal: AbortSignal,
): Promise<SignedUpload> {
const response = await fetch('/api/images/sign', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: file.type, size: file.size }),
signal,
})
if (!response.ok) throw new Error('Could not sign the upload')
return (await response.json()) as SignedUpload
}
export async function enableUploads(editor: Editor): Promise<void> {
await editor.enable([
imageUpload({
upload: presignedUploader({ getTarget: signUpload }),
// 5 MB
maxSize: 5 * 1024 * 1024,
onError: (error) => console.warn(error.code, error.file.name),
}),
])
}What happens:
- The user drops, pastes or picks an image.
imageUpload()checks the type (PNG, JPEG, GIF and WebP by default, never SVG) and size, and shows a placeholder with progress where the image will go. presignedUploaderasks your backend for a target, thenPUTs the file there, reporting progress.- The placeholder is replaced by the image with
publicUrl. Its alt text isnull, so it is marked as needing a description.
On failure the placeholder disappears and onError gets an ImageUploadError with a code (type, size, upload, src) and the file. The default kit shows and announces these errors for you.
The backend
Sign one object key per request, never a prefix, and check the type and size you are told against what you allow. Make the signature require the Content-Type header, so the stored object cannot be served as HTML.
A plain multipart endpoint works too: fetchUploader({ url: '/api/images' }) expects a JSON response with url.