Upload image using Multer in Node JS Express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for the web and mobile applications. Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.
Multer is a module which is used for handling multipart/form-data to upload files. Here is an example to upload an image.
step 1 : You have to install multer module. open command line in your project root directory and change the directory to node_modules then use the following command
$ npm install --save multer
Step 2 : In the view folder make a file name image.ejs and paste the following HTML
<form action="/uploadProfileImg" enctype="multipart/form-data" method="post" name="frm"> <input name="profile" type="file" /> <input name="submit" type="submit" value="submit" /> </form>
Step 3 : app.js file in root folder.The require method import the profile.js file under route folder. The app.post method has two parameter, first parameter for set url / route and second parameter is the js file where the uploading definition are there.
var profile = require('./routes/profile'); app.post('/uploadProfileImg',profile);
Step 4 : In the route/profile.js file, paste the following code.
var multer = require('multer'); var upload = multer({ dest: './public/images/users/' }) router.post('/uploadProfileImg',upload.single('profile'), function(req, res, next) { var id = req.session.user; db.query("update userregistration set profile_pic = '"+req.file.filename+"' where u_id = "+id, function(err,result){ if(err) throw err; res.end(err); }); res.redirect('profileSetting'); });
The image will be uploaded and the image name will be placed in the database table.