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