Closed vishnurs closed 8 years ago
It would be worth thinking about if we should include this straight in multer, in the meantime you can absolutely do it asynchronous.
multer.diskStorage({
destination: (req, file, cb) => {
const dir = '/my/nice/path'
fs.mkdir(dir, err => cb(err, dir))
}
})
Hope it helps :+1:
Actually, you might want to use the mkdirp
module:
const mkdirp = require('mkdirp')
multer.diskStorage({
destination: (req, file, cb) => {
const dir = '/my/long/path/with/many/levels'
mkdirp(dir, err => cb(err, dir))
}
})
We can also use async by adding a middleware in router before upload
var fs = require('fs')
var uploadPath = ''
app.post('/profile', checkUploadPath, upload.single('avatar'), function (req, res, next){
})
function checkUploadPath(req, res, next) {
fs.exists(uploadPath, function(exists) {
if(exists) {
next();
}
else {
fs.mkdir(uploadPath, function(err) {
if(err) {
console.log('Error in folder creation');
next();
}
next();
})
}
})
}
@vishnurs If the uploadPath
is static I would recommend doing the check only once instead of for every requests.
const multer = require('multer')
const mkdirp = require('mkdirp')
const uploadPath = '/my/nice/path'
const upload = muter({ dest: uploadPath })
mkdirp.sync(uploadPath)
app.post('/profile', upload.single('avatar'), (req, res, next) => {
// ...
})
@LinusU Yes. uploadPath
is not static in my case, it depends on the request parameters.
:ok_hand:
It would be worth thinking about if we should include this straight in multer, in the meantime you can absolutely do it asynchronous.
multer.diskStorage({ destination: (req, file, cb) => { const dir = '/my/nice/path' fs.mkdir(dir, err => cb(err, dir)) } })
Hope it helps 👍
This will always try to make directory. You don't have a condition that checks whether directory exists or not. With your code, only first time upload will be successful and later uploads will end up in exceptions. Please update your code for checking if directory exists or not.
I would like to know if there is any option to check if upload path exists, if not create the path.
I can do this in multer.diskStorage -> destination function, I would like to do the check using async or promises. Is there any support for this in multer?