File Uploads in Node.js and Express.js
Published: 2023-08-24 06:52:37

## 
1. Introduction
2. What is Multer in Nodejs?
3. Steps-by-step tutorial of File Upload Using Multer in Node.js and Express
4. Conclusion

**Introduction**

Uploading files is a fundamental operation for many applications. In the context of Node.js, utilizing the Multer middleware along with Express can provide an effective and streamlined approach to handling file uploads. Multer is specifically designed to streamline the process of receiving, storing, and managing incoming files.

In this tutorial, we will delve into the topic of file uploads using Multer in a Node.js environment. We'll explore how to implement file uploads for various types of media, such as images and videos, using both the Multer library and the Express framework. So, let's kick off our tutorial and delve into the world of file uploads in Node.js using Multer.

**What is multer in NodeJs?**

Multer in Node.js is a middleware designed to manage the handling of multipart/form-data requests, specifically tailored for file uploads. It functions on the foundation of the busboy parser, chosen for its high efficiency in processing such data.

The primary role of Multer is to simplify the intricate process of file uploads within a Node.js application. It is available as an NPM package and serves as a valuable tool for addressing the complexities associated with file handling. Multer seamlessly integrates into the middleware stack of Node applications, facilitating the smooth reception, storage, and management of uploaded files.

Furthermore, Multer offers a range of functionalities, including the ability to rename files, define size limits, specify acceptable file types, and implement file filtering. These features collectively contribute to making file uploads in Node.js a more manageable and streamlined task.

**Step-by-Step Tutorial: File Upload with Multer in Node.js and Express**

**Initial Setup**

```
create Directory
mkdir MulterApp
cd MulterApp
```
**Define package.json file**
For creating one [creating node application], run this command:
`npm init`

**Install dependencies**
We only have two dependencies to be installed- Express and Multer. So here are the commands

```
To install Express-
npm install express --save
To install multer-
npm install multer --save
```
To begin, create a file named anything you prefer; for instance, let's call it app.js. We'll focus on keeping all the code within this app.js file for simplicity. After that, load the Express module by utilizing the require() function. Lastly, you can proceed to craft the code snippet mentioned below, which sets up the fundamental Express server.

```
//app.js
const express = require('express');
const path = require('path');
const app = express()
const PORT = process.env.PORT || 3000
app.get(‘/’, (req, res) => { 
    res.send(‘multer demo’); 
});
app.listen(PORT, () => {
    console.log('Server is up on port ' + port);
})
```
After this you can also setup node devtool using following npm

```
to install nodemon npm
npm install nodemon -g
```
Run this command to verify-
**nodemon app.js**

**Hit http://localhost:3000, and you should see “multer demo” in your window.**

**Adding Multer**

For simplicity purpose, I’ll store all the uploaded files in the local folder. Write the below-mentioned code for loading multer in our app.js file

```
const multer = require(‘multer’);
```
Using multer you can upload single image and multiple images.

**Multer Storage for Single Image Upload**

Now, let's move on to the next step, which involves specifying a storage location for the files. Multer simplifies this process by offering an option to store our files on the disk. We will establish a designated directory to store all the files and assign them new identifiers.

To initiate this, create a directory named "images" in the root directory.

Feel free to proceed with these instructions to effectively manage file storage using Multer

```
//image upload
const imageStorage = multer.diskStorage({
    // Destination to store image     
    destination: 'images', 
      filename: (req, file, cb) => {
          cb(null, file.fieldname + '_' + Date.now() 
             + path.extname(file.originalname))
            // file.fieldname is name of the field (image)
            // path.extname get the uploaded file extension
    }
});

if **images** directory is not there multer will create it.

```
**Destination:** The "destination" parameter serves as a directive guiding the application on where to store uploaded images. This can be expressed as a string, such as './uploads'. If the designated destination is unavailable, Multer will rely on the default directory for temporary files. When utilizing a function as the destination, it's imperative to create the required directory. If a string is provided, Multer will automatically generate the directory.

**Filename:** "Filename" dictates the name a file should adopt within the designated folder. Should you omit the file name, a randomly generated name devoid of an extension will be assigned. This function involves three parameters: the request object, the file object, and a callback function. The callback incorporates two arguments:

null: Representing the absence of errors.
file.originalname: In this demonstration, I've retained the original uploaded file name. However, you have the flexibility to choose any name you prefer.

```
const imageUpload = multer({
      storage: imageStorage,
      limits: {
        fileSize: 1000000 // 1000000 Bytes = 1 MB
      },
      fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(png|jpg)$/)) { 
           // upload only png and jpg format
           return cb(new Error('Please upload a Image'))
         }
       cb(undefined, true)
    }
})
```
1. The multer() method takes an object with storage property.
2. The limits property describes the maximum size of the file.

The fileFilter() method is for security reasons. I have validated files before it is uploaded to the servers. Here, it will accept only two extensions – .png and .jpg. After this, it’s time to create the post route. We will make a POST request to localhost:3000/uploadImage.

Add the following code in the app.js-

```
// For Single image upload
router.post('/uploadImage', imageUpload.single('image'), (req, res) => {
     res.send(req.file)
}, (error, req, res, next) => {
     res.status(400).send({ error: error.message })
})
```
In my implementation, I've employed imageUpload.single('image') to facilitate the upload of a single file. As previously explained, Multer enriches the request with a file object, encompassing valuable metadata about the uploaded file. Within the single() method, the specific field name is passed—a field name that aligns with what will later be entered in Postman.

Please proceed with this configuration as it offers a seamless mechanism to handle single-file uploads using Multer.

**To test the endpoint, open Postman.**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dznbkym3savt4qtti0c9.png)
**Upload Multiple Images using Multer in Node JS**

Moving forward, our objective is to enable the uploading of multiple files using Multer. To facilitate this, Multer offers an additional function called arrays(fieldname[, max_count]), which conveniently handles an array of files, all of which share a common fieldname. This function provides the flexibility to set a constraint, max_count, to specify the maximum permissible number of files. The resultant array of files will be stored within req.files.

It's important to note that for this process, there's no necessity to create a distinct storage setup. Instead, we will continue using the same storage configuration established earlier.

Feel free to proceed with this approach, as it streamlines the process of managing multiple-file uploads using Multer.

```
// For multiple image upload

router.post('/uploadBulkImage', imageUpload.array('images', 5),    (req, res) => {
   res.send(req.files)
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})
```
I trust you found this tutorial on file uploads (Images) using Node's Multer to be beneficial. By following this guide, you've had the opportunity to grasp the process of uploading image files using Multer within a Node.js and Express.js environment. Implementing file upload functionality need not be challenging; Multer simplifies handling multipart/form-data effortlessly in Node.js.