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

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:

npm install multer --save

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


const multer = require('multer');

var storage = multer.diskStorage({
	destination: (req, file, cb) => {
	  cb(null, __basedir + '/uploads/')
	},
	filename: (req, file, cb) => {
	  cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
	}
});

var upload = multer({storage: storage});

app.post('/api/uploadfile', upload.single("uploadfile"), (req, res) => {
  console.log(req.file);
  res.json({'msg': 'File uploaded successfully!', 'file': req.file});
});

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

var storage = multer.diskStorage({
	destination: (req, file, cb) => {
	  cb(null, __basedir + '/uploads/')
	},
	filename: (req, file, cb) => {
	  cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
	}
});

var upload = multer({storage: storage});
  • 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?

app.post('/api/uploadfile', upload.single("uploadfile"), (req, res) => {
	...
});

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

Below is an example of a file object:

{ 
  fieldname: 'uploadfile',
  originalname: 'JSA.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'C:\\nodejs\\NodeJS-Express-Multer-Upload-MultipartFile/uploads/',
  filename: 'uploadfile-1526121642916-JSA.png',
  path: 'C:\\nodejs\\NodeJS-Express-Multer-Upload-MultipartFile\\uploads\\uploadfile-1526121642916-JSA.png',
  size: 59632 
}
KeyDescription
fieldnameField name specified in the form
originalnameName of the file on the user’s computer
encodingEncoding type of the file
mimetypeMime type of the file
sizeSize of the file in bytes
destinationThe folder to which the file has been saved
filenameThe name of the file within the destination
pathThe full path to the uploaded file

Practice

We create a NodeJS/Express project as below structure:


/NodeJS-Express-Multer-Upload-MultipartFile
	/app
		/uploadfile
			upload.multipartfile.js
	/node_modules
	/uploads
		/*contains upload files - DiskStorage of Multer*/
	package.json
	package-lock.json
	server.js

Setting up NodeJS/Express project

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


mkdir NodeJS-Express-Bootstrap4-Card-Image
cd NodeJS-Express-Bootstrap4-Card-Image

Then init NodeJS project:


NodeJS-Express-Multer-Upload-MultipartFile>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodejs-express-multer-upload-multipartfile)
version: (1.0.0)
description: Building a NodeJS-Express RestAPI for upload multipart file with Multer module
entry point: (index.js) server.js
test command:
git repository:
keywords: NodeJS, Express, Multer, MultipartFile, RestAPI, Upload-File
author: grokonez.com
license: (ISC)
About to write to C:\Users\pc\Desktop\nodejs\NodeJS-Express-Multer-Upload-MultipartFile\package.json:

{
  "name": "nodejs-express-multer-upload-multipartfile",
  "version": "1.0.0",
  "description": "Building a NodeJS-Express RestAPI for upload multipart file with Multer module",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Multer",
    "MultipartFile",
    "RestAPI",
    "Upload-File"
  ],
  "author": "grokonez.com",
  "license": "ISC"
}


Is this ok? (yes) yes

-> Install Express, Multer:


npm install express multer --save

-> See package.json file:


{
  "name": "nodejs-express-multer-upload-multipartfile",
  "version": "1.0.0",
  "description": "Building a NodeJS-Express RestAPI for upload multipart file with Multer module",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Multer",
    "MultipartFile",
    "RestAPI",
    "Upload-File"
  ],
  "author": "grokonez.com",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "multer": "^1.3.0"
  }
}

Upload Router

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


module.exports = function(app){
	const multer = require('multer');
	
	var storage = multer.diskStorage({
		destination: (req, file, cb) => {
		  cb(null, __basedir + '/uploads/')
		},
		filename: (req, file, cb) => {
		  cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
		}
	});
	
	var upload = multer({storage: storage});
	
	app.post('/api/uploadfile', upload.single("uploadfile"), (req, res) => {
	  console.log(req.file);
	  res.json({'msg': 'File uploaded successfully!', 'file': req.file});
	});
}

Server.js

./server.js file:


var express = require('express');
var app = express();
var bodyParser = require('body-parser');

global.__basedir = __dirname;

require('./app/uploadfile/upload.multipartfile.js')(app);

// Create a Server
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port)
 
})

Run & Check results

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


Request Type: POST
Address: http://localhost:8081/api/uploadfile
Body: form-data
Header: Null
Key: uploadfile
value: select a file from machine

NodeJS-Express-Multer-Upload-MultipartFile-postman

-> Server Logs:

\NodeJS-Express-Multer-Upload-MultipartFile>node server.js
App listening at http://:::8081
{ fieldname: 'uploadfile',
  originalname: 'JSA.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'C:\\nodejs\\NodeJS-Express-Multer-Upload-MultipartFile/uploads/',
  filename: 'uploadfile-1526121642916-JSA.png',
  path: 'C:\\nodejs\\NodeJS-Express-Multer-Upload-MultipartFile\\uploads\\uploadfile-1526121642916-JSA.png',
  size: 59632 }

-> 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 grokonez | May 15, 2018.

Last updated on April 3, 2021.



Related Posts


Got Something To Say:

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

*