Skip to main content

Command Palette

Search for a command to run...

Handling File Uploads in Express with Multer

Updated
4 min read
Handling File Uploads in Express with Multer

File uploads are a common requirement for many web applications, whether it’s uploading user avatars, attaching documents, or handling multimedia content. In this guide, we’ll explore how to handle file uploads in Node.js using the Express framework. Additionally, we’ll implement validation to ensure uploaded files meet specific criteria such as file size and file type.

Prerequisites:

Before proceeding, ensure you have Node.js and npm installed on your system.

Setting up the Project:

First, let’s set up a new Node.js project. Create a new directory for your project and navigate into it using your terminal or command prompt.

mkdir file-upload-example
cd file-upload-example

Initialize a new Node.js project by running the following command and following the prompts:

npm init -y

Next, install the necessary dependencies:

npm install express multer

Understanding Multer:

Multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. It integrates seamlessly with Express and provides a convenient way to handle file uploads.

Setting up the Express Server and Multer:

Create a new JavaScript file (e.g., app.js) in your project directory to set up the Express server.

Paste the below code in the app.js file.

// app.js

const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();

// Configure storage engine and filename
const storage = multer.diskStorage({
  destination: './uploads/',
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Initialize upload middleware and add file size limit
const upload = multer({
  storage: storage,
  limits: { fileSize: 1000000 } // 1MB file size limit
}).single('myFile'); // 'myFile' is the name attribute of the file input field

// File upload route
app.post('/upload', (req, res) => {
  upload(req, res, (err) => {
     if (err) {
       console.error(err);
       return res.status(500).json({ error: err });
      }
     if (!req.file) {
        return res.status(400).json({ error: 'Please send file' });
      }
      console.log(req.file);
      res.send('File uploaded!');
  });
});

app.listen(3000, () => console.log('Server started on port 3000'));

Looking into the Code:

  • We require the necessary modules: express, multer, and path.
const express = require('express');
const multer = require('multer');
const path = require('path');
  • We configure Multer to specify the destination folder where uploaded files will be stored and set a filename function to determine the name of the uploaded file.
const storage = multer.diskStorage({
  destination: './uploads/',
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});
  • The upload middleware is initialized using Multer. We set the storage engine and define limits such as file size.
const upload = multer({
  storage: storage,
  limits: { fileSize: 1000000 } // 1MB file size limit
}).single('myFile');
  • In the /upload route, we handle the POST request. The upload middleware processes the file upload, and we handle errors and success responses accordingly.

Adding File Type Validation:

To ensure that only specific file types are allowed, we can add file type validation using a custom function within the Multer middleware.

// Add file type validation
const upload = multer({
  storage: storage,
  limits: { fileSize: 1000000 },
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  }
}).single('myFile');

// Check file type
function checkFileType(file, cb) {
  const filetypes = /jpeg|jpg|png|gif/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb('Error: Images only! (jpeg, jpg, png, gif)');
  }
}

Test the application

Run the project by running below command in terminal.

node app.js

go to postman and create a Http request and in body tab select form-data and add a field myFile and in dropdown select file and attach your file and send the request.