0

I am a novice at NodeJS and I created a service to upload images to a shared location. However, I need to set the upload folder dynamically based on the user id: for e.g. the folder will be /uploads/{userid}/file.txt

I am not sure how to do it and I have been searching today with no luck.

The NodeJS service looks like:

var express = require('express')
var multer = require('multer')

var Storage = multer.diskStorage({
destination: function (req, file, callback) {
    callback(null, "./Uploads");
},
filename: function (req, file, callback) {
    callback(null, file.fieldname + "_" + Date.now() + "_" + 
             file.originalname);
     }
}); 

var upload = multer({ Storage: Storage })

var app = express()


app.post('/upload', upload.array('uploads[]', 12), function (req, res, next) 
{
     return res.end("Files uploaded sucessfully!.");
})

Thank you for the help.

M Y Essa
  • 115
  • 2
  • 7
  • TBH, you don't have to dynamically set the upload directory, you just have to move the file using the `fs` module once the upload progress is completed – Felix Fong Jan 03 '18 at 17:35
  • thank you @FelixFong, I decided to use uuid from [link](https://stackoverflow.com/a/40523220/2704079) because I get a unique ID for each file and can then link it to a UserID in the database. – M Y Essa Jan 03 '18 at 20:05

1 Answers1

0

Try this

app.use(multer({
  dest: './uploads/',
  "rename" : function (fieldname, filename, req, res) {
    return path.join(fieldname, req.params.user_id+".txt");
  }
})
santosh singh
  • 27,666
  • 26
  • 83
  • 129