How to add file upload with Node.js and Express?

Sometimes, we want to add file upload with Node.js and Express.

In this article, we’ll look at how to add file upload with Node.js and Express.

How to add file upload with Node.js and Express?

To add file upload with Node.js and Express, we can use the express-fileupload package.

To install it, we run

npm i express-fileupload

Then we use it by writing

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

app.use(fileUpload());

app.post('/upload', (req, res) => {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  const {
    sampleFile
  } = req.files;

  sampleFile.mv('/somewhere/on/your/server/filename.jpg', (err) => {
    if (err) {
      return res.status(500).send(err);
    }
    res.send('File uploaded!');
  });
});

to call app.use with the middleware we get from calling fileUpload.

Then we check if req.files is defined and has any entries in it in the POST /upload route handler.

If req.files isn’t defined or has no length, then we return a 400 response.

Otherwise, we get the file and call mv to save the file as '/somewhere/on/your/server/filename.jpg'.

The callback we pass into mv when mv is done.

Conclusion

To add file upload with Node.js and Express, we can use the express-fileupload package.