dev-resources.site
for different kinds of informations.
Multer - Build RestAPI to upload a MultipartFile to NodeJS/Express
https://grokonez.com/node-js/multer-build-restapi-to-upload-a-multipartfile-to-nodejs-express
Multer - Build RestAPI to upload a MultipartFile to NodeJS/Express
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
tr:nth-child(even) {
background-color: #e6eeff;
}
th, td {
padding: 5px;
}
th {
text-align: center;
}
In the tutorial, we show how to use Multer middleware for building a RestAPI to upload MultipartFile to NodeJS/Express web-application.
Related posts:
Multer - Upload MultipartFile
Multer is a NodeJS middleware for handling multipart/form-data
. It will not process any form which is not multipart (multipart/form-data
). To install Multer module, use below command:
npm install multer --save
Follow below segment code to build RestAPIs for handling a uploaded file:
const multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + '/uploads/')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
}
});
var upload = multer({storage: storage});
app.post('/api/uploadfile', upload.single("uploadfile"), (req, res) => {
console.log(req.file);
res.json({'msg': 'File uploaded successfully!', 'file': req.file});
});
Multer provides a diskStorage engine that we have a full control on storing files to disk.
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + '/uploads/')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
}
});
var upload = multer({storage: storage});
-
destination
is used to determine within which folder the uploaded files should be stored. -
filename
is used to determine what the file should be named inside the folder.
How the below segment code work?
app.post('/api/uploadfile', upload.single("uploadfile"), (req, res) => {
...
});
-> Multer adds a file object to the request object. req.file
is the uploadfile file.
https://grokonez.com/node-js/multer-build-restapi-to-upload-a-multipartfile-to-nodejs-express
Featured ones: