Uploading images in Node.js with Multer

There are three ways to handle file uploads in Node.js: store the images directly on your server, store the image binary data or base64 string data in your database, and use Amazon Web Service (AWS) S3 buckets to transfer your images. .


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


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 navigate to it by running the following command:

mkdir multer-tutorial
cd multer-tutorial

Then initialize npm in your project directory by running:

npm init -y

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

  • emphatically:Express is a Node.js framework that provides a robust set of features for web and mobile applications. It makes it easier to build backend applications with Node.js.
  • Multer: Multer is an express middleware that simplifies uploading and saving images to your server.

Install the packages with the node package manager by running:

npm install express multer

Then create a app.js file in the root of your project and add the block of code below to create a standard 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 more in your app.js File.

const multer = require("multer");

more requires a storage engine that contains information about the folder where the uploaded files are stored and what the files are called.

A more storage engine is created by the . to invoke disk storage method on the imported more module. This method returns a Storage Engine implementation configured to store files on the local file system.

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

the second building, file name, is a function that determines the names of the uploaded files. Three parameters are needed: requires, Fileand a callback request (cb). requires is the Express Request object, File is an object that contains 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.

See also  Download and install NVIDIA's GeForce now

Add the code block below to your 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, set the destination property to”./Pictures”, so the images are saved in your project’s folder in a Pictures folder. Then, in the callback, you passed zero as the error and a template string as the file name. The template string consists of a timestamp generated by calling Date.now() to ensure that the image names are always unique, two hyphens to separate the file name and timestamp, and the original name of the file, which can be accessed through the File object.

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

Then you need to initialize more with the storage engine.

Add the code block below to your app.js file to initialize multer with the storage engine:


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

more returns a Multer instance that provides several methods for generating middleware that processes files uploaded in multipart/form-data format.

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

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

Step 3: Add image validation rules

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

Update your multiconfig object with the block of code below:

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

In the code block above you have a . added limits property to the configuration object. This property is an object that specifies different limits for incoming data. You set the file size property, which sets the maximum file size in bytes to 1 millionwhich corresponds to 1 MB.

See also  12 Easy Ways to Improve Your Lightroom Editing Skills

Another validation rule you can add is the fileFilter property, an optional feature to control which files are uploaded. This function is called for each file being processed. This function has the same parameters as the file name function: requires, Fileand cb.

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

Add the code block below to your app.js file to implement the file filtering 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 checkFileType function has two parameters: File and cb.

In the code block above, ua . defined file types variable that stores a regex expression with the allowed image file extensions. Then you called the to test method on the regex expression.

The to test method checks for a match in the passed string and returns WHERE or false depending on whether it finds a match. Then you pass the uploaded file name, which you have access to file.originalnamein the module of the path extname method, which returns the extension of the string path to it. Finally, you chain the JavaScript to LowerCase string function to the expression to process images with their extension names in uppercase.

Checking the extension name alone is not enough, as extension names can be easily edited. To ensure that only images are uploaded, you must mime type at. You can access a file’s mime type property through the file.mimetype. So, you check for the mime type property using the to test method as you did for the extension names.

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

See also  Connect your Raspberry Pi to a cellular network

Finally, add the fileFilter property to your multi-configuration.

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

Step 4: Using Multer as an Express Middleware

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

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

Add the code block below to your app.js file to create a route handler for uploading a single image:

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 mentioned the only method on the upload variable, which stores your multiconfiguration. This method returns a middleware that handles a “single file” associated with the specified form field. Then you passed the image as the form field.

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

Add the code block below to your 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 mentioned the series method on the upload variable, which stores your multiconfiguration. This method takes two arguments – a field name and a maximum number – and returns middleware that handles multiple files that share the same field name. Then you passed Pictures as the shared 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 saving images directly to 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.