How to Upload file using node.js and Express.Js with multer module?
Create a Project
c:\> npx express --view=ejs crud_api
Initialise and Configure Our Project
File Name :
c:\crud_api> npm init -y
npm install
Install express and other dependencies
File Name :
c:\crud_api> npm install express --save
install Body Parser :-
File Name :
c:\crud_api> npm install body-parser --save
MySql Install
File Name :
c:\crud_api> npm install mysql --save
Nodemon Install
File Name :
c:\crud_api> npm install --save-dev nodemon
Install Multer
File Name :
npm install --save multer
create upload-form.js page under view directory.
File Name : views/upload_form.js
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="/upload_myfile" method="POST" enctype="multipart/form-data">
<label>Avatar</label>
<input type="file" name="myfiles" >
<button type="submit">Upload</button>
</form>
</body>
</html>
creates directory middlewares under root directory.
create a file upload-middleware.js in the middlewares folder.
You must include the Multer module by using require('multer')
File Name : middlewares/upload_middleware.js
var multer = require('multer');
module.exports.files={
storage:function(){
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/files/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
return storage;
},
allowedFile:function(req, file, cb) {
if (!file.originalname.match(/\.(pdf|doc|txt|jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
req.fileValidationError = 'Only files are allowed!';
return cb(new Error('Only files are allowed!'), false);
}
cb(null, true);
}
}
Create Controller :-
include a middleware file using require('../middlewares/upload_middleware')
File Name : controllers/upload_controller.js
var multer = require('multer');
var fileUpload= require('../middlewares/upload_middleware');
module.exports={
fileUploadForm:function(req,res){
res.render('upload-form');
},
uploadFile:function(req,res){
var upload = multer({
storage: fileUpload.files.storage(),
allowedFile:fileUpload.files.allowedFile
}).single('file');
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
res.send(err);
} else if (err) {
res.send(err);
}else{
res.render('upload-form');
}
})
}
}
Create Routes to Upload Multiple Files
File Name : routes/upload_route.js
const express = require('express');
const router = express.Router();
const fileUploadController= require('../controllers/upload_controller');
router.get('/upload',fileUploadController.fileUploadForm);
router.post('/upload',fileUploadController.uploadFile);
module.exports = router;
Include the Router File in app.js
File Name : app.js
var ur = require('./routes/upload_route');
;
app.use('/', ur);
Output :-
http://localhost:3000/upload
open your browser and Enter the above URL in your browser
after that Select files from your device by pressing the ctrl/shift key
finally Click submit button to upload files successfully.
File upload code
File Name : app.js
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, DIR);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
let upload = multer({storage: storage});
app.post('/api/v1/upload',upload.single('profile'), function (req, res) {
message : "Error Occurs! in image upload."
if (!req.file) {
console.log("file not received");
message = "Error! in image upload."
res.render('index',{message: message, status:'danger'});
} else {
console.log('file received successfully');
console.log(req);
var sql = "INSERT INTO `file`(`name`, `type`, `size`) VALUES ('" + req.file.filename + "', '"+req.file.mimetype+"', '"+req.file.size+"')";
var query = db.query(sql, function(err, result) {
console.log('inserted data');
});
message = "Successfully! File uploaded";
res.render('index',{message: message, status:'success'});
}
});
message =''
app.get('/', function(req, res) {
res.render('index', message);
});
Previous
Next