Nodejs File upload using Multer and Expressjs

multer_file_upload

Nodejs File upload using Multer and Expressjs

If you are build your backend using nodejs and want to upload file from your andoroid device. Below is the snippet using nodejs , multer and expressjs.

Requirements:

const  express  =  require('express')
const  app  =  express()
const  util  =  require('util')
const  port  =  3000;

var  multer  =  require('multer')
//set the storage folder for the muttler
var  storage  =  multer.diskStorage({
destination:  function (req, file, cb) {

//set the upload directory
cb(null, 'upload')
},
filename:  function (req, file, cb) {
//set name for the uploaded file
cb(null, file.originalname  +  '-'  +  Date.now())
}
})

var  upload  =  multer({ storage:  storage });

//GET
app.get('/', function (req, res) {
res.send("hello");
});

//upload function
//Uploaded file will be saved in the upload folder
app.post('/upload', upload.single('file'), function (req, res, next) {

console.log("file received "  +req.file.filename);

res.send({upload:"success",fileName:req.file.filename});
})

//listen
app.listen(port, () =>  console.log(`Example app listening on port ${port}!`))

Start your node server now you can upload file to

http://localhost:3000/upload.

Use postman to test your upload file function

Postman parameter

  • Select body 'content-type ' as ' form-data'
  • Set 'key' as 'file' then select file
  • Click send button

Comments