Skip to content

Uploading files in node.js and express using express-fileupload

To handle file uploads in your node.js / express APIs, there are many middleware packages readily available. express-fileupload is one of those simple express middleware available as an npm package. In this tutorial, we will discuss how to handle file uploads with Node.js and Express backend and save uploaded files on the server using express-fileupload.

Advertisements

Install dependencies

First of all, add express-fileupload dependency to your package.json.

npm install express-fileupload --save

Enable file upload in express

Enable file upload in your express application by adding the following lines in app.js.

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



....


// Enable file upload using express-fileupload
app.use(fileUpload({
  createParentPath: true
}));
Advertisements

Code your file upload API

You can access your file with req.files.filename. In the code below, we upload a file and move it to uploadedFiles directory. In the response we return the name, type and size of the uploaded file.

routes.post('/upload', async (req, res) => {
    try {
        if(!req.files) {
            res.send({
                status: false,
                message: 'Error: No file uploaded'
            });
        } else {
            let uploadedFile = req.files.uploadedFile;
            uploadedFile.mv('./uploadedFiles/' + uploadedFile.name);
            res.json({
                message: 'File is uploaded',
                data: {
                    name: uploadedFile.name,
                    mimetype: uploadedFile.mimetype,
                    size: uploadedFile.size
                }
            });
        }
    } catch (err) {
        res.json({Error: "Error while uploading file."})
    }
});

module.exports = routes;
Advertisements

Test your API

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.