Thursday, June 25, 2020

Learn to upload files using Multer and Node.js in just 5 minutes


Did you reach a stage in your project where you require a feature to upload files to your database?, or You simply want to learn how uploading of files to the database is done? Don't worry, I got all your answers covered in this article.

Uploading files is one of the most common features these days, and the majority of websites tend to use it somewhere. File uploads in Node.js seem to be a tedious job, but luckily we have multer for the rescue.

Surely there are many options available such as Multiparty and Formidable, but after seeing the popularity, the number of downloads, and ratings. I would say Multer is one of the best-suited options right now.

What exactly is Multer?
Multer is a Node.js Middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of the busboy for maximum efficiency. 
Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

Let's proceed towards the central part of this article .i.e, how to use multer in our application?. We'll go step by step.

Create the directory and initialize the project - STEP 1
This is, in fact, a very first step for every node.js project. Create the directory and use npm init to create the package.json file.
 mkdir file-upload-multer  
 cd file-upload-multer  
 npm init  

Install the dependencies - STEP 2
 npm install express multer --save  
If you are reading this article, then I am assuming that you must be aware of what express is. If not, you must go and study it.
Here's a simple explanation of express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Create server.js in the directory - STEP 3
Travel to the directory in the command prompt and then type
 touch server.js  
Create the server using Express - STEP 4
If you know what express is. Understanding this code will be like a breeze for you.

Open the server.js in your favorite text editor and type the following code.
 var express = require(‘express’);  
 const app = express();  
 const port = 3000;  
 app.get(‘/’, (req, res) => {  
   res.send(‘hello people’);  
 });  
 app.listen(port, () => {  
   console.log(‘listening to the port: ‘ + port);  
 });  
You must be aware of the fact that testing is one of the essential steps during the development of any application. So Let's now proceed towards the testing of the code used till now.
In your terminal type
 node server.js  
Now open this URL http://localhost:3000 in your browser. 


If you can see an exactly similar message on your screen. Congratulations! You are halfway through.

Easy? Now let's go a step ahead and add multer to our project.

Add multer in server.js - STEP 5
 var multer = require('multer');  
 var upload = multer({dest:'uploads/'});  
Hey, what is this dest? Can you explain to me the second line?
These questions must be arousing in your mind. Let me answer these.

Here dest is the path where the file will be stored .i.e, the file which we will upload will be saved in uploads/ directory.

Now,  create a post route which will upload the file.
 app.post('/single', upload.single('profile'), (req, res) => {  
  try {  
   res.send(req.file);  
  }catch(err) {  
   res.send(400);  
  }  
 });  

Also, let me tell you that multer is capable of handling multiple uploads as well. Upload.single argument is used to upload a single file. As mentioned earlier, Multer adds a file object to the request. This file object contains metadata related to the file.

Its time for the testing again :)
I am using Postman for checking this route.




After the upload is complete, you will notice, an uploads folder is created in your main directory, and it contains the uploaded file. But wait, why it doesn't have any extension. How can we get the extension?.

Surprisingly Multer also got a solution for this ;)

If you want more controls over the uploads, you have to use the storage option instead of dest. Multer by default ships with storage engines DiskStorage and MemoryStorage.

Implementing DiskStorage Engines - STEP 6
 var storage = multer.diskStorage({  
   destination: function(req, file, cb) {  
     cb(null, './upload');  
    },  
   filename: function (req, file, cb) {  
     cb(null , file.originalname);  
   }  
 });  
What is the use of diskStorage?
DiskStorage engine gives full control of storing files to disk. In the code above, I created a storage object using diskStorage.
The options destination and filename determine where the file should be stored.

Destination
the destination is used to determine the folder in which the uploaded file should be stored. The callback function contains a string to name the location (For, e.g., ./upload)
If no destination is provided, the default directory will be used to storing the uploaded file.

Filename
the filename is used to give a name to the uploaded file. If no filename directions are provided, each file will be given a random name that doesn't include any file extension. Also, Multer will not append any file extension for you, your function should return a filename complete with a file extension.

To reflect the storage changes, you have to modify the upload variable as
 var upload = multer({ storage: storage })  

Congratulations on your first successful single file upload using Multer. ;)

Should I proceed one step further?
Of course, why not, now I'll teach you how you can upload multiple files.

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

You would have already noticed that there's only a single change in the code. 
Yes, I just changed upload.single to upload.array. upload.array is used when you need to upload multiple files at once.

We are going to test the application for the one last time;)


Got similar results?
Pat on your Back, You successfully learned and implemented the multer to upload single and multiple files.

Conclusion
Time to look at what we learned. Multer is a Node.js Middleware for handling multipart/form-data, which is primarily used for uploading files. And by following these simple steps, you can implement multer in your next project. However, if you think this is an important one, consider bookmarking this.

Should I write an article that differentiates between multer and its equivalent dependencies?
Previous Post
Next Post

post written by:

Hi, Navjyot Singh is a coder, content maker and a freelance developer who's pursuing an undergraduate Engineering degree in Computer Science. He started out as a web developer but later picked up the mobile as his favourite platform to develop applications. A Writer by day and coder by night is loathed to discuss himself as the third person but can be persuaded to do so from time to time.

0 comments: