Express file upload

express-file-upload

In this tutorial, we will be walking you through an example of how to develop a simple express API for file upload.

Sometimes it happens while developing an express API we may need file upload functionality.

Although there are several packages available for nodejs eco-system. However, for the purpose of this tutorial, we will be focusing on a popular package named “express-fileupload“.

Agenda

So, the agenda for this tutorial will be to create a basic express API for file upload.

Install express-fileupload and other required nodejs packages

To upload files on the express server firstly, we need to initialize our project

with the following command:

npm init -y

then we have to install all the required packages which we can do using:

npm install express express-fileupload

After that, create a folder in the current working directory where you want to save the uploaded files. For instance, we have named it Uploads.

then create an entry point index.js file in our root directory.

const express = require("express");
const fileUpload = require("express-fileupload");
const app = express();
app.use(fileUpload());
const PORT = 3000;
app.post("/upload", async (req, res) => {
  const { files } = req;
  const { sampleFile } = files;
  const uploadPath = `${__dirname}/Uploads/${sampleFile.name}`;
  const hasFiles = Object.keys(files).length > 0;
  try {
    if (!(files && hasFiles)) {
      return res.status(400).send("No files were uploaded.");
    }
    res.send("File Uploaded Successfully!");
    sampleFile.mv(uploadPath);
  } catch (error) {
    res.status(500).send(error);
  }
});
app.listen(PORT, () => {
  console.log("Server is Up running on PORT : ", PORT);
});

Afterward, files that we’ll upload, will get saved inside our Uploads directory.

Testing our express file upload API

At last, we need to test our application and for that, we have to create a simple form where we will POST our file.

<html>
  <body>
    <form ref='uploadForm' 
      id='uploadForm' 
      action='http://localhost:3000/upload' 
      method='post' 
      encType="multipart/form-data">
        <input type="file" name="sampleFile" />
        <input type='submit' value='Upload!' />
    </form>     
  </body>
</html>
nodejs server started
Running the node server.
html code to upload file in nodejs
Opening HTML file with live server
choose a file to upload in nodejs server
choose a file
file choosen upload on nodejs
file chosen
file uploaded on nodejs server
file uploaded

Conclusion

In summary, I want to conclude that it is super easy to upload files in nodejs.

Indeed it was so much fun to make this tutorial, I enjoyed making it a lot, hope you people find it useful.

Still, if you have any confusion, please feel free to ask in the comment section below.

Also, Don’t forget to appreciate in the comment section.

THANK YOU!