Skip to content

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.

  1. Add @hamur/blob to the app and to modules. With no blob key it stores on the disk under .data/blob on bun, node, static and under hamur dev, and in R2 on cloudflare. For S3, R2 over S3 or any host without a disk, set the driver:
ts
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" },
  },
})
  1. A handler whose input holds a File is the upload: Hamur sends it as multipart/form-data. form sets the limits, which answer 413 when passed. ensureBlob checks 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 sandboxing content-security-policy and nosniff, so a hostile one cannot run script. serve streams the stored file, with ranges and ETags:
ts
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("/")}`),
})
  1. 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 fetch works too:
ts
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.