Upload multiple files to Cloudflare R2, using Honojs on node.js
To upload multiple files from a browser to Cloudflare R2 using Honojs on Node.js, you’ll need to set up an endpoint to handle multipart/form-data requests and then interact with the Cloudflare R2 API to store the files.
Here’s a basic JavaScript program that demonstrates how to do this:
const { Hono } = require('hono');
const { formidable } = require('formidable-serverless');
// Initialize Hono app
const app = new Hono();
// Endpoint to handle file uploads
app.post('/upload', async (c) => {
// Parse the multipart form data
const form = new formidable.IncomingForm();
const files = await new Promise((resolve, reject) => {
form.parse(c.req, (err, fields, files) => {
if (err) reject(err);
resolve(files);
});
});
// Assuming you have set up Cloudflare R2 client
// Replace 'r2Bucket' with your actual R2 bucket instance
for (const file of Object.values(files)) {
// Create a stream to read the file
const stream = fs.createReadStream(file.filepath);
// Upload the file to Cloudflare R2
await r2Bucket.put(file.originalFilename, stream, {
httpMetadata: {
contentType: file.mimetype,
},
});
}
// Respond with a success message
return c.text('Files uploaded successfully!');
});
// Start the server
app.listen({ port: 3000 }, () => {
console.log('Server running on port 3000');
});
This code uses the formidable-serverless package to parse the uploaded files and the hypothetical r2Bucket object to interact with Cloudflare R2. You’ll need to replace 'r2Bucket' with your actual Cloudflare R2 bucket instance and handle authentication as required by Cloudflare.
Please note that this is a simplified example and doesn’t include error handling or security features like authentication, which you should implement in a production environment. Also, ensure you have the necessary packages installed and configured in your Node.js project.
Remember to consult the Hono documentation and Cloudflare R2 documentation for more detailed information and to adapt the code to fit your specific use case.
Revised:
const { Hono } = require('hono');
const { multipart } = require('multipart-parser');
// Initialize Hono app
const app = new Hono();
// Endpoint to handle file uploads
app.post('/uploadfile', async (c) => {
let prefix = "uploadtest";
const rawBody = Buffer.from(await c.req.arrayBuffer());
// Parse the 'content-type' header to get the boundary for multipart parsing
const boundary = c.req.headers.get("content-type").split(";")[1].split("=")[1];
const parts = multipart.parse(rawBody, boundary);
// Process each part of the multipart form data
for (const part of parts) {
if (part.name === "prefix") {
// Decode the prefix if provided
prefix = new TextDecoder().decode(part.data);
console.log("prefix:", prefix);
}
}
for (const part of parts) {
if (part.filename) {
// Decode the filename to handle UTF-8 characters
const fileName = decodeURIComponent(escape(part.filename));
console.log("filename:", fileName);
// Create an object with the file data to be uploaded
const dataObj = {
"Body": part.data,
"Bucket": 'mybucket', // Replace with your actual bucket name
"Key": `${prefix}/${fileName}`
};
// Upload the file to Cloudflare R2
await s3putobject(dataObj);
}
}
// Respond with a success message
return c.text('Uploaded successfully!');
});
// Start the server
app.fire();
In this code:
- We’re using the
multipart-parserlibrary to parse the multipart form data. - The
prefixvariable is used to create a directory structure in the R2 bucket. - The
s3putobjectfunction is assumed to be a custom function that handles the interaction with Cloudflare R2’s API to upload the file.
Please ensure that you replace 'mybucket' with your actual Cloudflare R2 bucket name and implement the s3putobject function according to Cloudflare R2’s API specifications.
If you have any further questions or need additional assistance, feel free to ask. Happy coding! 😊