NodeJS File Upload Using Multer

A lifelong learner. Love to travel. Listen to music.
Search for a command to run...

A lifelong learner. Love to travel. Listen to music.
No comments yet. Be the first to comment.
Check the source code here Authentication is an important portion for web application. From client side, like a mobile application must require a secure authentication to the server and *passport* is a prominent helper. Here I’m developing a simple ...
Best Practices for Path Structure, Versioning, and Error Handling

Understanding the Performance Implications of async and defer Attributes

Overview static: Default position. It does not allow setting properties like top, bottom, left, right, z-index relative: Acts the same as static. but allows positioning it relatively by putting properties like top, bottom, left, right, z-index absolu...

Overview When an element in the browser has a conflict of styles, the browser uses a set of rules to determine which style should be rendered. This set of rules is defined as CSS Selector Specificity. For instance, for an element, if we have the foll...

Master block, inline, flex, and grid to build better web layouts

Fork or clone the source code here

Multer is a Node.js middleware, used to upload or handle multipart/form-data, on the top of Busboy. Here I’ll explain the basic procedure of uploading a file in Node.js server.
First Get the seed code.
Install dependencies.
Create database named myproject.
Install multer dependency.
Configure multer.
Voila!!! test through Postman
Get the seed code from here.
First install all the node modules:
npm install
Create database named, myProject.
mongo
use myproject
Now run the project using
node server.js
or
nodemon
You have to see the line in console
The magic happens on port 8080
Install multer
npm install --save multer
Add the multer object to your routing file, routes/user/index.js
var multer = require('multer');
We will upload the file in public/images/uploads directory. So our multer will contain the following configaration:
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public/images/uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({storage: storage});
Now the multer is ready to upload the file in public/images/uploads folder
Now we add the multer configuration in the routing file and add a dummy routing.
Now the routes/user/index.js will be looked like:
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
var multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public/images/uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({storage: storage});
router.post('/fileUpload', upload.single('image'), (req, res, next) => {
MongoClient.connect(url, (err, db) => {
assert.equal(null, err);
insertDocuments(db, 'public/images/uploads/' + req.file.filename, () => {
db.close();
res.json({'message': 'File uploaded successfully'});
});
});
});
module.exports = router;
var insertDocuments = function(db, filePath, callback) {
var collection = db.collection('user');
collection.insertOne({'imagePath' : filePath }, (err, result) => {
assert.equal(err, null);
callback(result);
});
}
Now our code is ready for test.
We will perform API test using Postman:
In postman
Request Type: POST
Address: [http://localhost:8080/user/fileUpload](http://localhost:8080/user/fileUpload)
Body: form-data
Header: Null
Key: image
value: select a file from your machine

Now In your project structure, public/images/uploads, you will find the uploaded file and as well as in the database of myproject the file path is saved already.
So Here we are, completed the basic file uploading using multer in node.js and express.js server. Stay tuned and if there is a confusing term or something, response below or create an issue in *github*.