Nodejs File upload using Multer and Expressjs

sapan
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

Post a Comment

2Comments
  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice and straightforward tutorial! File upload functionality is an essential part of many modern web applications, and Multer makes the process much easier for Node.js developers. Similar secure upload and data management techniques are also important for government platforms like the registration process, uhr payslip login password etc, where reliability and safe handling of employee information are critical. Thanks for sharing this helpful example.

    ReplyDelete
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !