Search code examples
node.jsmulter

multer: dynamic destination path


I am writing a node application and I was looking for something to upload files on the server. I could get files to upload when there was only one static directory. But I need to make directories per user and then upload files to those, according to the user that's logged in. I looked stuff up but everything that I try ends in an Error: ENOENT: no such file or directory, open ... error. What I am trying to do currently is this -

let storage = multer.diskStorage({
  destination: function(req, file, cb) {
    let dest = path.join(__dirname, './documents', 'somenameigetfromtheuser');
    let stat = null;
    try {
      stat = fs.statSync(dest);
    }
    catch (err) {
      fs.mkdirSync(dest);
    }
    if (stat && !stat.isDirectory()) {
      throw new Error('Directory cannot be created');
    } 
    cb(null, dest);
  }
});

let upload = multer({
  storage: storage,
  dest: 'documents/'
});

app.post('/testUpload', upload.single('testfile'), (req, res) => {
  res.json({
    test: 'test'
  })
});

There is a similar question that has been answered but it doesn't work that way for me because I want the directory name from the request object.

When I remove the storage property in my multer initialization, the files are stored in the documents directory with a random name. I want the file to have its original name and I want it to be stored in a directory where I get the name of the directory from the req object.
Help a brother out, thanks!


Solution

  • In my project I use multer as follow:

    1.Store the file first in a common directory, like /tmp/.

    2.Copy/move the file anywhere you want, to CDN in my case, and to a user folder in yours.

    3.Remove the original file in /tmp if needed.

    And maybe let upload = multer({ storage: storage, dest: 'documents/' }); you should remove the dest here since you specified dest in storage, right?