Upload multiple files to Cloudflare R2, using Honojs on node.js

technology

5 months ago

post image

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-parser library to parse the multipart form data.
  • The prefix variable is used to create a directory structure in the R2 bucket.
  • The s3putobject function 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! 😊

Top rated comment:

Make your comment up here!

Leave a comment

Posting, please wait...
Please type a message first!

You may also like:

D o you want to connect with people who share your interests, passions, and goals? Do you want to express yourself, showcase your talents, and discover new opportunities? Do you want to enjoy a safe and enjoyable platform that offers everything you need for your daily computing needs? If you answered yes to any of these questions, then you should join NXplan.com, the new all-in-one social platform that features blog, messaging, chat, inbox, and marketplace.

NXplan.com is more than just a social network.

It’s a social ecosystem that allows you to create, communicate, and collaborate with others in a variety of ways. You can:
Create your own blog and share your thoughts, opinions, and experiences with the world. You can also follow other bloggers and get inspired by their content. Message your friends and family and stay in touch with them. You can also make new friends and join groups that match your interests.
Chat with other users and have fun conversations. You can also join live events and webinars and learn from experts and influencers. Manage your inbox and organize your emails. You can also send and receive files, photos, and videos with ease. Explore the marketplace and find products and services that suit your needs. You can also sell your own products and services and earn money.

NXplan.com is designed to provide you with a safe and enjoyable platform that respects your privacy and security.

You can: Control your own data and decide who can see and access your information. Report and block any abusive or inappropriate content or users. Enjoy a spam-free and ad-free environment that does not track or sell your data. Access the platform from any device and any browser, without any downloads or installations. NXplan.com is free to join and use, and you can get started in minutes. All you need is a valid email address and a password. You can also customize your profile and settings to make it your own.

Ready to give it a try?

Join NXplan.com today and discover a new way of socializing online. You’ll be amazed by what you can do and who you can meet on NXplan.com. Don’t miss this opportunity to join the next big thing in social media. Register now and start your NXplan journey.

Technology is nothing. What's important is that you have a faith in people, that they're basically good and smart, and if you give them tools, they'll do wonderful things with them

Steven Jobs

post image
post image