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 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);
});

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

Testing our 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>
express file upload - start server
express file upload – start server
open live server
open live server
choose a file
choose a file
file selected
file chosen
file upload success
success

Conclusion

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!

One thought on “Express file upload

Leave a Reply

Back To Top