本文へ移動

ファイルアップロード ​

multipart/form-data を使ってファイルをアップロードできます。アップロードされたフィールドは c.req.parseBody() で取得できます。

基本的な例 ​

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,
  })
})

アップロードサイズの制限 ​

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}`)
  }
)

複数のファイル ​

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,
    })),
  })
})

保存前の検証 ​

アップロードされたファイルをディスクに書き込んだり別のサービスに転送したりする前に、必要なフィールドが存在するかを検証し、ファイル名、MIME タイプ、サイズなどのメタデータを確認してください。

関連情報 ​

MIT ライセンスで公開されています。