Open1

HonoとCloudflare Workersでファイルをアップロードする

Godai HoriGodai Hori
index.ts
import { Hono } from "hono";
import { cors } from "hono/cors";

const app = new Hono();

app.use('/*', cors())

app.post("/avatar", async (c) => {
  const body = await c.req.parseBody()
  const file = body.avatar as File
  const bucket = c.env.BUCKET
  const filename = `avatars/${Math.random()}-${file.name}`;
  const response = await bucket.put(filename, await file.arrayBuffer(), {
    httpMetadata: {
      contentType: file.type,
    }
  });

  return c.json({
    message: `put ${filename} successfully!`,
    object: response,
    filename,
  }, 200)
});

export default app;
wrangler.toml
name = "images"
main = "src/index.ts"
compatibility_date = "2023-02-11"
usage_model = "bundled"
env = { }
node_compat = true

[triggers]
crons = [ ]

[[r2_buckets]]
binding = 'BUCKET' # <~ valid JavaScript variable name
bucket_name = 'mosya'