Handle file uploads in Node JS with Formidable

Handle file uploads in Node JS with Formidable

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

While handling file uploads via the form in Express, you might have tried Multer. It is good but Formidable is awesome when it comes to simplicity without having to deal with middleware.

The formidable module is used for parsing both the form data and the file uploads. It's very easy to use and can be easily integrated.

Installation

Visit npmjs or click here or you can install the package by using the below command.

npm i formidable

The highlights of this module are (according to npmjs):

  • Fast (~900-2500 MB/sec) & streaming multipart parser
  • Low memory footprint
  • Graceful error handling
  • Very high test coverage

app.js

const express = require("express")
const fs = require("fs");
const formidable = require("formidable");

const app = express();

app.post("/handle-uploads", (req, res) => {
  const form = formidable();
  form.parse(req, async (err, fields, files) => {
    // your form fields will be found inside 'fields' variable
    // your form files will be inside files variable
  });
});

app.listen(3300, (err) => {
  if (err) console.log(err);
  console.log("Server started on port 3300");
});

Let's say we want to upload the file to a particular location suppose inside the uploads directory.

For that, we have to specify the path inside form.parse().

// inside app.post("/handle-uploads", (req, res) => {

const form = formidable();
form.parse(req, async (err, fields, files) => {
  if (err) {
    return res.status(400).json({
      status: "Failure",
      msg: "Some error occured " + err.message,
    });
  }
  let oldPath = files.nameOfTheField.path;
  let newPath = `./uploads/${files.nameOfTheField.name}`;
  fs.rename(oldPath, newPath, (err) => {
    if (err) {
      return res.status(400).json({
        status: "Failure",
        msg: "Failed to upload file. " + err.message,
      });
    }
    res.status(201).json({
      status: "Success", 
      msg: "File uploaded successfully"
    });
  });
});

Thanks

I hope this post will help you in handling file uploads easily. If you found this code helpful, please share this post with others and also leave a comment below and let me know your thoughts.

Thanks for the time, see you in my next post.

 
Share this