How to Upload Images in Node.js Using Multer

There are three main ways to handle file uploads in Node.js: saving images directly to your server, saving image binary data or base64 string data in your database, and using Amazon Web Service (AWS) S3 containers to save and manage your data. Pictures.

Here you will learn how to use Multer, a Node.js middleware, to upload and save images directly on your server in Node.js applications in a few steps.

Step one: Create the development environment

The code used in this project is available on the GitHub repository and is free for you to use under the MIT license.

First, create a project folder and navigate to it by running the following command:

mkdir multer-tutorial
cd multer-tutorial

Next, initialize npm in the project directory by running:

npm init -y

Next, you will need to install some dependencies. Dependencies required for this tutorial include:

  • pass: Express is the Node.js framework that provides a powerful set of features for web and mobile applications. It’s easy to build backend applications with Node.js.
  • molter: Multer is a fast broker that simplifies uploading and saving images to your server.

Install packages with the node package manager by running:

npm install express multer

Next, create a file app.js file in the root directory of your project and add the code block below to create a basic Express server:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.listen(port, ()=>{
console.log(`App is listening on port ${port}`);

Step 2: Configure Multier

First, import molter in your app.js a file.

const multer = require("multer");

molter It requires a storage drive that contains information about the directory where the downloaded files will be stored and how to name the files.

a molter Storage drive is created by calling office storage Method on the imported file molter lonliness. This method returns a file storage drive Execution is configured to store files on the local file system.

An object has two properties: Destinationwhich is a string or function that defines where the uploaded images are stored.

second characteristic, file name, is a function that specifies the names of uploaded files. It requires three parameters: wantedAnd the a filecall back (cb). wanted is express Request Goal, a file is an object that contains information about the processed file, and cb It is a callback that specifies the names of uploaded files. The callback function takes the error and filename as arguments.

Add the below code block to your app.js File to create a storage drive:

const storageEngine = multer.diskStorage({
destination: "./images",
filename: (req, file, cb) => {
cb(null, `${}--${file.originalname}`);

In the above code block, I set a file Destination Property “./ PicturesThus, the images will be stored in your project directory in the . format Pictures Folder. Then, in the callback, I passed no thing as an error and a template string as the file name. The template string consists of a timestamp generated by the invocation () To ensure that image names are always unique, two conditions are required to separate the file name and timestamp, and the original file name, which can be accessed from a file Goal.

The resulting strings from this template will look like this: 1663080276614 – example.jpg.

Next, you need to configure molter With storage drive.

Add the below code block to your app.js File to configure multer with storage drive:

const upload = multer({
storage: storageEngine,

molter Retrieves an instance of Multer that provides several ways to create a middleware that handles uploaded files Multipart/data model Formula.

In the above code segment, you pass a config object with the extension storage Set the property to Storagewhich is the storage drive you created earlier.

Currently, your Multer configuration is complete, but there are no validation rules that guarantee that only images can be saved to your server.

Step 3: Add Image Verification Rules

The first verification rule you can add is the maximum size allowed to upload an image to your app.

Update your multer config object using below code block:

const upload = multer({
storage: storageEngine,
limits: { fileSize: 1000000 },

In the above code block, I added a file border Configuration object property. This property is an object that defines different boundaries for the incoming data. You set a file File size The property, by which the maximum file size is set in bytes 1000000which is equivalent to 1 megabyte.

Another validation rule you can add is filter property , which is an optional function to control which files are uploaded. This function is called for each file being processed. This function takes the same parameters as file name Function: wantedAnd the a fileAnd the cb.

To make your code more clean and reusable, you will strip all the filtering logic into a function.

Add the below code block to your app.js File to implement the file filter logic:

const path = require("path");
const checkFileType = function (file, cb) {
const fileTypes = /jpeg|jpg|png|gif|svg/;
//check extension names
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: You can Only Upload Images!!");

The Check file type The function takes two parameters: a file And the cb.

In the above code block, I have defined a file File types A variable that stores a regex expression with allowed image file extensions. After that, you call a test method on regex expression.

The a test The method checks for a match in the passed string and returns TRUE or False Depending on whether it will find a match or not. Next, you pass the name of the uploaded file, from which you can access it file.originalnamein the path unit extname , which re-extends the string path to it. Finally, you hook into JavaScript toLowerCase String to Expression to handle images with capitalized extension names.

It is not enough to check the extension name alone, as extension names can be easily edited. To ensure only images are loaded, you should check the MIME type as well. You can access a file mime type property through file.mimetype. So, you have to check out mime type property using a test way as you did with extension names.

If both conditions return true, it will return the callback with no thing and true, or it returns a callback with an error.

Finally, add an extension filter property to configure your multer.

const upload = multer({
storage: storageEngine,
limits: { fileSize: 10000000 },
fileFilter: (req, file, cb) => {
checkFileType(file, cb);

Step 4: Using Multer as a Quick Agent

Next, you have to implement the path handlers that will handle the image uploads.

Multer can handle both single and multiple image uploads depending on the configuration.

Add the below code block to your app.js File to create a routing handler for single image uploads:"/single", upload.single("image"), (req, res) => {
if (req.file) {
res.send("Single file uploaded successfully");
} else {
res.status(400).send("Please upload a valid image");

In the above code block, I called a file Not connected method on Download variable, which stores the composition of your moleuter. This method returns a middleware that handles a “single file” associated with the given form field. Then you pass picture as a form field.

Finally, check if the file has been uploaded by File wanted object in a file its origin. If so, you are sending a success message, or sending an error message.

Add the below code block to your app.js File to create a routing handler for multiple image uploads:"/multiple", upload.array("images", 5), (req, res) => {
if (req.files) {
res.send("Muliple files uploaded successfully");
} else {
res.status(400).send("Please upload a valid images");

In the above code block, I called a file matrix array method on Download variable, which stores the composition of your moleuter. This method takes two arguments – a field name and a max number – and returns middleware that handles multiple files that share the same field name. Then I passed Pictures as the common form field and 5 the maximum number of images that can be uploaded at once.

Advantages of using a Moulter

Using Multer in Node.js applications simplifies the complex process of uploading and saving images directly to your server. Multer is also based on busboy, which is the Node.js module for parsing incoming form data, which makes it very effective for parsing form data.