How to Upload Images in Node.js Using Multer

There are three ways to handle file uploads in Node.js: storing the images directly on your server, storing the image’s binary data or base64 string data in your database, and using Amazon Web Service (AWS) S3 buckets for Store and manage your images.


Learn how to use Multer, a Node.js middleware, to upload and save images directly to your server in Node.js applications in just a few steps.


Step 1: Set up development environment

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

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

mkdir multer-tutorial
cd multer-tutorial

Next, initialize npm in your project directory by running:

npm init -y

Next you need to install some dependencies. The dependencies required for this tutorial include:

  • To express:Express is a Node.js framework that provides a robust feature set for web and mobile applications. It makes it easy to build backend applications using Node.js.
  • Muller: Multer is an express middleware that simplifies the process of uploading and storing images on your server.

Install the packages using the node package manager by running:

npm install express multer

Next, create one app.js File in the root of your project and add the following block of code to create a simple 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 Multer

Import first mother in your app.js File.

const multer = require("multer");

mother requires a storage engine that contains information about the directory where the uploaded files will be stored and how the files will be named.

A mother Storage engine is created by calling disk space method on the imported mother Module. This method returns a StorageEngine Implementation configured to store files on the local file system.

It takes a configuration object with two properties: targeta string or function that specifies where the uploaded images will be stored.

The second property filename, is a function that gets the names of the uploaded files. It takes three parameters: necessary, fileand a callback (cb). necessary is the Express inquiry Object, file is an object containing information about the processed file, and cb is a callback that determines the names of the uploaded files. The callback function takes error and filename as arguments.

Add the following block of code to yours app.js File to create a storage engine:


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

In the code block above you set the target property to “./Pictures‘, so the images will be stored in your project’s directory in a pictures folder. Then you passed the recall zero as error and a template string as filename. The template string consists of a time stamp generated by a call date.now() to ensure that image names are always unique, two dashes to separate the filename and timestamp, and the original name of the accessible file file Object.

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

Next you need to initialize mother with the storage engine.

Add the following block of code to yours app.js File to initialize Multer with storage engine:


const upload = multer({
storage: storageEngine,
});

mother returns a Multer instance that provides several methods for generating middleware that handles uploaded files multipart/form-data Format.

In the code block above, you pass a configuration object with a storage property set to StorageEnginethe storage engine you created earlier.

Currently your Multer configuration is complete, but there are no validation rules to ensure only images can be stored on your server.

Step 3: Add image validation rules

The first validation rule you can add is the maximum size allowed for an image to be uploaded to your application.

Update your Multer configuration object with the following code block:

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

In the code block above, you added a limits property on the configuration object. This property is an object that specifies various restrictions on incoming data. You set the file size Property that sets the maximum file size in bytes 1000000which corresponds to 1 MB.

Another validation rule you can add is the File Filter property, an optional feature to control which files are uploaded. This function is called for each processed file. This function uses the same parameters as the filename Function: necessary, fileand cb.

To make your code cleaner and more reusable, abstract all filter logic into a function.

Add the following block of code to yours 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!!");
}
};

That checkFileType The function takes two parameters: file and cb.

In the code block above, you defined a data types Variable storing a regex expression with the allowed image file extensions. Next, call them test Method for the regex expression.

That test The method looks for a match in the passed string and returns it Is correct or NOT CORRECT depending on whether it finds a match. Then pass the uploaded file name by which you can access it file.original namein the module of the path minor name method that returns the expansion of the string path to it. Finally, concatenate the JavaScript to lowercase string function to the expression to handle images with their extension names in upper case.

Checking the extension name alone is not enough as extension names can easily be edited. To ensure only images are uploaded, you also need to check the MIME type. You can access a file mime guy property by the file.mimetype. So you check them mime guy property with the test Method like you did for the extension names.

If both conditions return true, return the callback with zero and true, or you return the callback with an error.

Finally you add the File Filter property to your Multer configuration.

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

Step 4: Using Multer as Express Middleware

Next you need to implement route handlers that handle the image uploads.

Depending on the configuration, Multer can process both single and multiple image uploads.

Add the following block of code to yours app.js File to create route handler for single image upload:

app.post("/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 code block above, you called the single method on the upload Variable that stores your Multer configuration. This method returns a middleware that processes a “single file” associated with the specified form field. Then you passed picture as a form field.

Finally, check if a file has been uploaded via the necessary object in the file Property. If so, send a success message, otherwise send an error message.

Add the following block of code to yours app.js File to create a route handler for uploading multiple images:

app.post("/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 code block above, you called the Row method on the upload Variable that stores your Multer configuration. This method accepts two arguments – a field name and a maximum number – and returns middleware that processes multiple files with the same field name. Then you passed pictures as a common form field and 5 as the maximum number of images that can be uploaded at once.

Benefits of using Multer

Using Multer in your Node.js applications simplifies the otherwise complicated process of uploading and storing images directly on your server. Multer is also based on Busboy, a Node.js module for parsing incoming form data, making it very efficient for parsing form data.

Leave a Reply

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