sor4chi / hono-storage

A storage helper for Hono. Support disk, memory, S3, etc.
MIT License
99 stars 3 forks source link

How to upload image in S3 using hono and cloudfareworkers #59

Open BandiDhruv opened 3 months ago

BandiDhruv commented 3 months ago

here is my implementation of code import { Hono } from "hono"; import { S3Client } from "@aws-sdk/client-s3"; import { HonoS3Storage } from "@hono-storage/s3";

const client = (accessKeyId: string, secretAccessKey: string) => new S3Client({ region: "ap-southeast-2", credentials: { accessKeyId, secretAccessKey, }, });

const storage = new HonoS3Storage({ key: (_, file) => ${file.originalname}-${new Date().getTime()}.${file.extension}, bucket: "myblogiumbk1", client: (c) => client(c.env.AWS_ACCESS_KEY_ID, c.env.AWS_SECRET_ACCESS_KEY), }); userRoute.post('/api/upload', storage.single("file"), async (c) => { try { const { file } = await c.req.parseBody();

// Check if file exists and has a name if (!file ) { return c.json({ error: "Missing file or filename in request" }, 400); }

// Upload the file using storage // ... (your upload logic)

return c.text("Image uploaded successfully!"); } catch (e) { console.error(e); return c.json({ error: "Internal server error" }, 500); } });

can anyone tell me how to change my code so that I can upload image from when user inputs it and store it in my bucket

sor4chi commented 3 months ago

Hi, @BandiDhruv

Thank you for raising the issue.

Your code is actually already set up regarding uploading. The actual uploading process is written in the storage.single middleware, so it actually works on its own.

import { S3Client } from "@aws-sdk/client-s3";
import { HonoS3Storage } from "@hono-storage/s3";
import { Hono } from "hono";

const client = (accessKeyId: string, secretAccessKey: string) =>
  new S3Client({
    region: "ap-southeast-2",
    credentials: {
      accessKeyId,
      secretAccessKey,
    },
  });

const storage = new HonoS3Storage({
  key: (_, file) =>
    `${file.originalname}-${new Date().getTime()}.${file.extension}`,
  bucket: "myblogiumbk1",
  client: (c) => client(c.env.AWS_ACCESS_KEY_ID, c.env.AWS_SECRET_ACCESS_KEY),
});

const userRoute = new Hono();
userRoute.post("/api/upload", storage.single("file"), async (c) => {
  return c.text("Image uploaded successfully!");
});

export default userRoute;