expressjs / multer

Node.js middleware for handling `multipart/form-data`.
MIT License
11.55k stars 1.05k forks source link

Check if the upload folder path exists #287

Closed vishnurs closed 8 years ago

vishnurs commented 8 years ago

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?

LinusU commented 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:

LinusU commented 8 years ago

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))
  }
})
vishnurs commented 8 years ago

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();
          })
        }
     })
}
LinusU commented 8 years ago

@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) => {
  // ...
})
vishnurs commented 8 years ago

@LinusU Yes. uploadPath is not static in my case, it depends on the request parameters.

LinusU commented 8 years ago

:ok_hand:

collab-with-tushar-raj commented 5 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 👍

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.