Zum Inhalt springen

Datei-Upload ​

Du kannst Dateien mit multipart/form-data hochladen. Die hochgeladenen Felder sind über c.req.parseBody() verfügbar.

Einfaches Beispiel ​

ts
import { Hono } from 'hono'

const app = new Hono()

app.post('/upload', async (c) => {
  const body = await c.req.parseBody()
  const file = body['file']

  if (!(file instanceof File)) {
    return c.text('File is required', 400)
  }

  return c.json({
    name: file.name,
    size: file.size,
    type: file.type,
  })
})

Upload-Größe begrenzen ​

ts
import { Hono } from 'hono'
import { bodyLimit } from 'hono/body-limit'

const app = new Hono()

app.post(
  '/upload',
  bodyLimit({
    maxSize: 5 * 1024 * 1024, // 5 MiB
    onError: (c) => {
      return c.text('File too large', 413)
    },
  }),
  async (c) => {
    const body = await c.req.parseBody()
    const file = body['file']

    if (!(file instanceof File)) {
      return c.text('File is required', 400)
    }

    return c.text(`Uploaded ${file.name}`)
  }
)

Mehrere Dateien ​

ts
import { Hono } from 'hono'

const app = new Hono()

app.post('/upload', async (c) => {
  const body = await c.req.parseBody({ all: true })
  const value = body['file']

  const files = Array.isArray(value)
    ? value.filter((item): item is File => item instanceof File)
    : value instanceof File
      ? [value]
      : []

  if (files.length === 0) {
    return c.text('At least one file is required', 400)
  }

  return c.json({
    count: files.length,
    files: files.map((file) => ({
      name: file.name,
      size: file.size,
      type: file.type,
    })),
  })
})

Vor dem Speichern validieren ​

Bevor du hochgeladene Dateien auf die Festplatte schreibst oder an einen anderen Dienst weiterleitest, prüfe, ob die erwarteten Felder vorhanden sind, und kontrolliere Metadaten wie Dateiname, MIME-Typ und Größe.

Siehe auch ​

Veröffentlicht unter der MIT-Lizenz.