Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Prerequisites
3.
Procedure
3.1.
Create a directory
3.2.
Installation of dependencies 
3.3.
Create server.js file
3.4.
Creating server
3.5.
Adding Multer
3.6.
Use of DiskStorage
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

File upload with multer

Introduction

Multer in node.js is a middleware / npm package that handles multipart/form-data, but the primary task is to upload files. We use it when dealing with text-only data, such as name, password, email, etc. We need to specify the enctype attribute with multipart/form-data while uploading files. Forms that include file input type element, this value is required. Multer in node.js makes it easy to handle files efficiently. We will now see how to use Multer in node.js to manage and upload files with node.js and express.js

Prerequisites

Three things are needed to be done and known before learning how to upload files with Multer in node.js-

  • It would be helpful if you had a good understanding of HTML and CSS.
  • node.js should install, and you should have a prior working knowledge of it. 
  • Furthermore, you should understand command lines or terminals integrated into code editors and their commands. 

 

A common feature of most websites is a file upload. And we will now do this with the help of Multer with express.js. For maximum efficiency, Multer in node.js is written on top of bushboy. It adds a body object with the request object having a file object. Body objects have the text field's form values, and the file uploaded in the form is stored in the file object.

Procedure

Create a directory

Create a directory for the project and type the command npm init to create a package.json file.

make a new directory-

mkdir file-upload-multer 

move to the following directory-

cd file-upload-multer

initialize npm-

npm init

Installation of dependencies 

Install the required dependencies 

npm install express multer --save

OUTPUT-

Create server.js file

Create server.js by using the touch command, or if it doesn't work, use 

type nul >server.js

or

echo >server.js

Creating server

Create server using express.js by opening server.js file and typing following code-

var express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
 res.send('hello developers');
});
app.listen(port, () => {
 console.log('we are listening to the port: ' + port);
});

After typing the code, we have to save the file and run it using the command 

node server.js

OUTPUT-

To see the result, type the following URL 

http://localhost:3000

OUTPUT-

Congratulations! you have come so far and covered halfway.

Adding Multer

now add multer 

var multer = require('multer');
var upload = multer({dest:'uploads/'});

Here dest denotes the destination of the file where it will be stored. Furthermore, we create an endpoint that will upload the file.

app.post('/single', upload.single('profile'), (req, res) => {
 try {
 res.send(req.file);
 }catch(err) {
 res.send(400);
 }
});

 

Single files and multiple files can be uploaded with the help of Multer in node.js. Here upload.single command is for uploading a single file. A file object is added by Multer to the request. Metadata related to the file will be stored in this file object.

OUTPUT-

For better understanding have a look at this video -

Now you will notice the uploaded folder will be created in dest option means destination location, but the uploaded file will not contain any extension. We use the storage option instead of dest for having more control. Multer ships with storage engines DiskStorage and MemoryStorage

Use of DiskStorage

Use DiskStorage. We get complete control of storing files on a disk by using a disk storage engine. We will use the following code for creating storage.

var storage = multer.diskStorage({
 destination: function(req, file, cb) {
 cb(null, './upload');
 },
 filename: function (req, file, cb) {
 cb(null , file.originalname);
 }
});

and update upload variable 

var upload = multer({ storage: storage })

 

We have two options, destination and filename, available, which are functions used to determine where the file should be stored.

The folder in which the uploaded files should be stored is determined by destination. We can also be given a string, for example, '/desktop/upload .'operating system's default directory is used for storing temporary files when we don't provide any value for the destination. 

Creating the directory is our responsibility while providing the destination as a function—Multer whether the directory is created for you or not when we pass the string into it.

Furthermore, the file's name inside the folder is defined by filename, but if we don't give any representation, it is given any random name with no extension. As multer does not add an extension to your file, you must return the file name with the extension.

Both the request (req) are passed by each function and some information about the file (file) to aid the decision. If you want to have the same file name while saving, they were uploaded for that use file.originalname, I am using file.originalname, or you can use any name of your choice. after hitting the endpoint, you will notice that the uploaded files will be present in the mentioned folder with the same extension and name.

Now, a single file is uploaded successfully using multer. Similarly, we can upload multiple files, and we use a bulk endpoint for uploading multiple files. 

app.post('/bulk', upload.array('profiles', 4) , (req, res) =>{
 try {
 res.send(req.files);
 } catch(error) {
 console.log(error);
 res.send(400);
 }
});

Here upload. array is used instead of upload—single, which adds in the request object, an object files.

It would help if you got on hitting the bulk endpoint.

Frequently Asked Questions

  1. What is node.js?

A backend javascript runtime environment that is open source and cross-platform also runs on the v8 engine. It contains many packages, and one of them was a Multer in node.js about which we learned in this blog.

2. What is express.js?

It is a backend web application node.js framework, open-source software with an MIT license. 

Key Takeaways

Don't come to a halt here. Check out our Top 10 NodeJS Frameworks In 2021 | Coding Ninjas Blog. You can also check out the blog on the What is Node.js? Where, When & How To Use It? | Coding Ninjas Blog. Check out some books for react.js PHP vs NodeJS: A complete showdown | Coding Ninjas BlogJavaScript environment requirements.

Live masterclass