Upload different files in different folders using Multer in NodeJs

Abhinav Jain
2 min readApr 17, 2020

You will not find many blogs regarding Multer to upload files in a different folder on some basis of referencing.

Case 1: When you only want to upload files in different folders on the basis of the field name.

Note: The dir must be already present on the server. (You can also create those dynamically using FS module)

var assign = multer.diskStorage({
destination:function(req,file,cb){
const dir=’./public/uploads/’+file.fieldname;if(file.fieldname === “Assign1”){
cb(null,dir);
}else if(file.fieldname===”Assign2"){
cb(null,dir);
}else if(file.fieldname===”Assign3"){
cb(null,dir);
}else if(file.fieldname===”Assign4"){
cb(null,dir);
}else if(file.fieldname===”Assign5"){
cb(null,dir);
}
},
filename: function(req,file,cb){
cb(null,file.originalname)
}
})
var upload = multer({storage:assign});

The API routes will look like this.

app.post(‘/submitted’,upload.any()
,function(req,res,next){
res.send(‘<html>file uploaded</html>’)
})

Input tags will look like this

<form action=”/submitted” enctype=”multipart/form-data” method=”POST”>
<table>
<tr><p> <h4 class = “text-white”>Assignment 1 <input type=”file” name=”Assign1"></h4></p>
<br></tr>
<tr><p> <h4 class = “text-white”>Assignment 2 <input type=”file” name=”Assign2"></h4></p>
<br></tr>
<tr><p> <h4 class = “text-white”>Assignment 3 <input type=”file” name=”Assign3"></h4></p>
<br></tr>
<tr><p> <h4 class = “text-white”>Assignment 4 <input type=”file” name=”Assign4"></h4></p>
<br></tr>
<tr><p> <h4 class = “text-white”>Assignment 5 <input type=”file” name=”Assign5"></h4></p>
<br></tr>
<tr><button class=”button” type=”submit” >Submit</button> </tr>
</table>

</form>

All filename should be written carefully

Case 2: When folder must be dynamically created basis on some attribute like user id passed in the body with multiple files.

const multer = require('multer')
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const { userId } = req.body
const dir = ./uploads/${userId}
fs.exists(dir, exist => {
if (!exist) {
return fs.mkdir(dir, error => cb(error, dir))
}
return cb(null, dir)
})
},
filename: (req, file, cb) => {
const { userId } = req.body
cb(null, UserId-${userId}-Image-${Date.now()}.png)
}
})

const upload = multer({ storage })

--

--

Abhinav Jain

I am tech enthusiast. Trying all different ways to deal with problems