File uploads
Goal: accept an image from a form, refuse what is too large or not an image, keep it, and serve it back. This replaces readMultipartFormData and NuxtHub's blob upload.
- Add
@hamur/blobto the app and tomodules. With noblobkey it stores on the disk under.data/blobonbun,node,staticand underhamur dev, and in R2 oncloudflare. For S3, R2 over S3 or any host without a disk, set the driver:
import { defineConfig, env } from "hamur"
import blob from "@hamur/blob"
export default defineConfig({
framework: "react",
modules: [blob],
blob: {
driver: "s3",
bucket: "uploads",
endpoint: "https://ACCOUNT.r2.cloudflarestorage.com",
region: "auto",
accessKeyId: env("S3_KEY"),
secretAccessKey: env("S3_SECRET"),
dev: { driver: "fs", base: ".data/blob" },
},
})
- A handler whose
inputholds aFileis the upload: Hamur sends it asmultipart/form-data.formsets the limits, which answer 413 when passed.ensureBlobchecks the size and the type the client sent and throws a 400 with a message the user may see. That type is not proof of what is in the file; the files are served with a sandboxingcontent-security-policyandnosniff, so a hostile one cannot run script.servestreams the stored file, with ranges and ETags:
import { ensureBlob, useBlob } from "@hamur/blob/server"
import { defineHandler, type StandardSchemaV1 } from "hamur/server"
const fileInput: StandardSchemaV1<unknown, { file: File }> = {
"~standard": {
version: 1,
vendor: "docs",
validate(value) {
const file = (value as { file?: unknown } | undefined)?.file
return file instanceof File ? { value: { file } } : { issues: [{ message: "file is required", path: ["file"] }] }
},
},
}
export async function storeImage(file: File) {
ensureBlob(file, { maxSize: "2MB", types: ["image"] })
return useBlob().put(`images/${crypto.randomUUID()}`, file)
}
export const uploadImage = defineHandler({
route: "/api/images",
method: "POST",
input: fileInput,
form: { maxBodySize: 3 * 1024 * 1024, maxFileSize: 2 * 1024 * 1024, maxFiles: 1 },
handler: ({ file }: { file: File }) => storeImage(file),
})
export const image = defineHandler({
route: "/images/**:pathname",
method: "GET",
raw: true,
handler: ({ pathname }: { pathname: string[] }, { event }) => useBlob().serve(event, `images/${pathname.join("/")}`),
})
- Send it from the browser. The generated stub of the handler does this for you when you call it from a component; a plain form or
fetchworks too:
export async function sendImage(file: File): Promise<{ pathname: string }> {
const body = new FormData()
body.set("file", file)
const response = await fetch("/api/images", { method: "POST", body })
if (!response.ok) throw new Error(((await response.json()) as { message?: string }).message ?? "Upload failed")
return response.json() as Promise<{ pathname: string }>
}
Both handlers are open to everyone as written. Check the user before put and before serve, as in Auth with sessions. The body limit of the host sits over form: 4.5 MB on Vercel, 6 MB on Netlify. For bigger files use useMultipartUpload, which sends parts of 5 MiB or more.
See also: Blob, @hamur/blob reference, Handlers.