Search code examples
javascriptnode.jsexpressmulter

Node.js unique folder for each upload with multer and shortid


I'm using shortid for a unique id each upload and multer for the post handler.

I'm uploading some input aswell as an image. I'd like for each upload to be stored inside "upload/XXXXX" I'm generating the unique id on app.post(...) and would like to know how to send this id to multer.

Using a global variable would have it's problems if 2 posts were done at the same time correct?

var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, path.join(__dirname, 'uploads', XXXXX)); //Unique id for file is the same as Folder
  },
  filename: function (req, file, callback) {
    callback(null, XXXXX); //Unique id
  }
});

var upload = multer({
  storage: Storage
}).single('pic');

//tell express what to do when the route is requested
app.post('/fbshare', function (req, res, next) {
  let ui = shortid();
  upload(req, res, function (err) {
    if (err) {
      return res.end("Something went wrong!");
    }
    return res.end("File uploaded sucessfully!.");
  });
});

How can i passthrough ui to Storage from app.post() ? Or if you have a better solution I'm all ears.

Thank you


Final Solution

var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    fs.mkdir(path.join(__dirname, 'uploads', req.ui), function(){
       callback(null, path.join(__dirname, 'uploads', req.ui));
    });
  },
  filename: function (req, file, callback) {
    callback(null, req.ui + file.originalname.substring(file.originalname.indexOf('.'), file.originalname.length));
  }
});

var upload = multer({
  storage: Storage
}).single('pic');

//tell express what to do when the route is requested
app.post('/fbshare', function (req, res, next) {
  req.ui = shortid();
  upload(req, res, function (err) {
    if (err) {
      return res.end("Something went wrong!");
    }
    return res.end("File uploaded sucessfully!.");
  });

});


Solution

  • How about this?

    app.post('/fbshare', function (req, res, next) {
      req.ui = shortid(); // create the id in the request
    ....
    

    then in the multer

    var Storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, path.join(__dirname, 'uploads', req.ui)); //Unique id for     
    ....
    

    the same with filename