Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
BandiDhruv opened this issue May 23, 2024 · 1 comment
Open

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

BandiDhruv opened this issue May 23, 2024 · 1 comment

Comments

@BandiDhruv
Copy link

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
Copy link
Owner

sor4chi commented May 25, 2024

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants