Uploading image in Node.js using multer

devquora
devquora

Posted On: Feb 22, 2018

Uploading image in Node.js using multer

 

Creating API to Upload an Image in node using Multer

Multer is a middleware for node.js that processes multipart/form-data. It is basically used for uploading images and documents in Node. For maximum efficiency, Multer is written top of the busboy (A HTML form data parser ). In this tutorial, we are going to see how to upload an image, pdf or document in Node js. Step1: Installing Multer.

npm install --save multer

Step2: Create a new file name UploadController.js and add following code.

'use strict';
var multer = require('multer');

exports.uploadImage=function(req, res){

let storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {

cb(null, Date.now() + "_" + file.originalname)
}

});
let upload = multer({
storage: storage
}).single('image');
upload(req, res, function(err, result) {

if (err) {
 return res.status(422).send({
 status: false,
 message: "Something got wrong:Invalid Id",
 statusCode: 422,
 data: null
 });
} else {
return res.status(200).send({
 status: true,
 statusCode: 200,
 message: "Image Uploaded Successfully",
 data:{},
 });}

});

}

Conclusion after reading this article you will able to upload multipart/form-data in Node.js

    Please Login or Register to leave a response.

    Related Articles

    Node Js Tutorials

    How to enable cors in Node js

    In this article, we are going to see how to enable CORS ( Cross-Origin Resource Sharing ) in Node JS. CORS essentially means cross-domain requests. Cross-Origin Resource Sharing (CORS) is a mechanism ..

    Node Js Tutorials

    Scheduling CRON Jobs on Node js using node schedule

    Cron Jobs are used for scheduling tasks to run on the server.CRON Jobs are the most commonly used method to automate tasks on Server. In this article, we will see how to schedule Jobs in Node.js. We a..

    Node Js Tutorials

    Uploading image from url using Node js

    In this tutorial, we are going to see how to Upload an image from URL using Node Js. We have written a simple function In Node.js to save an image from URL to local disk/ server. Whenever we use login..