Reputation: 1
I tried going through the github repo of hono where they have helped us but still I am not able to figure out how to upload an image from user and store it in s3 bucket using hono web framework on cloudfare workers
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
Upvotes: 0
Views: 499
Reputation: 1
Was facing the same issue , Here is what i did :
app.post("/upload/single", async (c) => {
const s3 = new S3Client({
credentials: {
accessKeyId: c.env.ACCESS_KEY,
secretAccessKey: c.env.SECRET_ACCESS_KEY,
},
region: c.env.BUCKET_REGION,
});
const formData = await c.req.formData();
const file = formData.get("image");
if (!(file instanceof File)) {
return c.json({ error: "File is required" }, 400);
}
const docId = v4();
const arrayBuffer = await file.arrayBuffer();
const fileContent = new Uint8Array(arrayBuffer);
const params = {
Body: fileContent,
Bucket: c.env.BUCKET_NAME,
Key: `${docId}.${file.name.split(".").pop()}`,
ContentType: file.type,
};
const uploadCommand = new PutObjectCommand(params);
const response = await s3.send(uploadCommand);
console.log(response);
return c.json({ id: docId });
});
Upvotes: 0