Sunday, February 24, 2019

Uploading a file using Multer!!

Recently I got a  requirement of uploading a file. We are using NodeJS server, so I explored on NPM and found out very simple library called Multer. It is very simple to use, so sharing here.
                   For uploading a file, we need to know the location where we are going to store the file. For that we need to specify the location for the Multer as shown below. One parameter is destination in the line 20 where we need to specify the location in this case uploads folder in the current directory. Another parameter is filename un the line 23 with which we are going to store in the location. If filename not specified, random number will be given to that file name. 
                   After specifying destination and filename parameters, need to map these Multer storage fields to Multer as shown below in the line 29.

Now let's see how to upload file. While using uploading POST request, need to match the query which is coming in the request parameters as shown below in line 48. In this api , I am using 'file', so query parameter should be 'file', you can use any name, but i used file here. In the line 48, we are using upload.single('file'), upload is actually Multer configured storage in the above image line 29. If file uploading is successful, we will get file name in the call back as shown in the line 49. If file upload fails, this filename will be undefined.

If you want to validate the request before start uploading, just add the method in the POST request as shown below in the line 48. In this case I used a method name as validate, you can use whatever function name you want or even you can skip this validation if you don't want, in that case you just remove that validation method from the line 48.

Now let's see Downloading file. For downloading a file, there is no dependency with Multer, but as we are discussing about uploading a file, lets see downloading file as well.

For the complete code. Refer my github link here.

Happy Learning!!

Popular Posts