In this article we will understand to upload files in nodejs using express + multer package + ejs template.
In this article we will understand to upload file in nodejs using express+multer+ejs template
let express = require("express"),
ejs = require('ejs'),
app = express(),
path = require('path'),
multer = require('multer');
app.set('view engine', 'ejs'); // code to set the ejs for rendering template
let storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
app.get('/api/file', function(req, res) {
res.render('index')
})
app.post('/api/file', function(req, res) {
let upload = multer({
storage: storage,
fileFilter: function(req, file, callback) {
let ext = path.extname(file.originalname)
if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
return callback(res.end('Only images are allowed'), null)
}
callback(null, true)
}
}).single('userFile');
upload(req, res, function(err) {
res.end('File is uploaded')
})
})
let port = process.env.PORT || 3000
app.listen(port, function() {
console.log('Node.js listening on port ' + port);
})
In the above file, at the top we have created an app with express framework, below that we have included multer package for uploading task at server end. Below that we have set the uploading location of files and renaming of files.
Now we have create a get method with route '/api/file' which simply renders the form field. And on the post method with the same name we perform the actual task of file uploading using nodejs multer package.
In the above frontend part, we have simply a html page where we have a form having a file of input type file and a submit button. Download the zipped code for fully functional code.
Hope this was helpful to you! Thanks alot.