Multer
Written By: Avinash Malhotra
Updated on
Upload files in node using multer
Multer is used to upload files in Node JS and express js. Multer supports Multi Part forms only. To use multer to upload files, use enctype multipart/form-data in html form.
By default, all form in html are application/x-www-form-urlencoded. But Multer will works only with multipart/form-data.
Install Multer
npm i multer
Multipart Form
Multer use Multipart form only. By default in HTML, all forms are using enctype application/x-www-form-urlencoded. So tio use multer, set enctype multipart/form-data in html form.
Multipart encoding send uploaded file data in parts. That's why its call Multipart.
<form action="/upload" method="post" enctype="multipart/form-data">
<label>Upload Picture: <input type="file" name="pic"> </label>
</form>
Multer usage
Multer can be used to upload single or multiple files. Here are some live examples of how to upload single or multiple files using multer.
Multer Example
const express=require('express');
const app=express();
const multer = require('multer')
const upload = multer({ dest: 'src/public/uploads/' })
app.post('/upload',upload.single('pic'),(req,res)=>{
// req.file is the picture
// req.body is text inputs
res.status(200).send("File Uploaded");
});
app.listen(3000,()=>{
console.log(`App running`);
});
Upload Multiple files
const express=require('express');
const app=express();
const multer = require('multer')
const upload = multer({ dest: 'src/public/uploads/' })
app.post('/upload',upload.array('pics',4),(req,res)=>{
// req.files is array of files
// req.body is text inputs
res.status(200).send("Files Uploaded");
});
app.listen(3000,()=>{
console.log(`App running`);
});
Upload Files with fields
const express=require('express');
const app=express();
const multer = require('multer')
const upload = multer({ dest: 'src/public/uploads/' })
const fields=upload.fields([
{ name: 'pic', maxCount: 1 },
{ name: 'gallery', maxCount: 4 }
]);
app.post('/upload',fields,(req,res)=>{
// req.files['pic'][0] is file
// req.files['gallery'] is array of files
res.status(200).send("Files Uploaded with fields");
});
app.listen(3000,()=>{
console.log(`App running`);
});
storage
disk storage engine gives full control to store files. disk storage gives two options, destination and filename. We can also change file name using disk storage engine. See example
const express=require('express');
const app=express();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'src/public/uploads/')
},
filename: function (req, file, cb) {
//cb(null, file.originalname); // for original name
cb(null, Date.now() + path.extname(file.originalname))
}
});
const upload=multer({storage:storage});
app.post('/upload',fields,(req,res)=>{
res.status(200).send("Files Uploaded with fields");
});
app.listen(3000,()=>{
console.log(`App running`);
});