Multer – Build RestAPI to upload a MultipartFile to NodeJS/Express

In the tutorial, we show how to use Multer middleware for building a RestAPI to upload MultipartFile to NodeJS/Express web-application.

Related posts:
NodeJs/Express RestAPIs – POST/GET/PUT/DELETE requests

Multer – Upload MultipartFile

Multer is a NodeJS middleware for handling multipart/form-data. It will not process any form which is not multipart (multipart/form-data). To install Multer module, use below command:

Follow below segment code to build RestAPIs for handling a uploaded file:

Multer provides a diskStorage engine that we have a full control on storing files to disk.

  • destination is used to determine within which folder the uploaded files should be stored.
  • filename is used to determine what the file should be named inside the folder.

How the below segment code work?

-> Multer adds a file object to the request object. req.file is the uploadfile file.

Below is an example of a file object:

Key Description
fieldname Field name specified in the form
originalname Name of the file on the user’s computer
encoding Encoding type of the file
mimetype Mime type of the file
size Size of the file in bytes
destination The folder to which the file has been saved
filename The name of the file within the destination
path The full path to the uploaded file

Practice

We create a NodeJS/Express project as below structure:

Setting up NodeJS/Express project

Create a folder ‘NodeJS-Express-Multer-Upload-MultipartFile’:

Then init NodeJS project:

-> Install Express, Multer:

-> See package.json file:

Upload Router

./app/uploadfile/upload.multipartfile.js file:

Server.js

./server.js file:

Run & Check results

Start NodeJS server, then make a POST request with PostMan:

NodeJS-Express-Multer-Upload-MultipartFile-postman

-> Server Logs:

-> Uploaded File:

NodeJS-Express-Multer-Upload-MultipartFile-results

Sourcecode

To run below sourcecode, follow the guides:


step 0: download & extract zip file -> we have a folder ‘NodeJS-Express-Multer-Upload-MultipartFile’
step 1: cd NodeJS-Express-Multer-Upload-MultipartFile
step 2: npm install express multer –save
step 3: node server.js
step 4: makes a POST request: http://localhost:8081/api/uploadfile

-> Sourcecode:

NodeJS-Express-Multer-Upload-MultipartFile

By JavaSampleApproach | May 15, 2018.

Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*