Node.js 每次上传的唯一文件夹,带有 multer 和 shortid

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

我使用 shortid 作为每个上传的唯一 ID,并为 post 处理程序使用 multer。

我正在上传一些输入​​内容和一张图片。我希望每次上传都存储在 "upload/XXXXX" 中 我正在 app.post(...) 上生成唯一 ID,想知道如何将此 ID 发送到 multer。

如果 2 post 同时完成,使用全局变量会有问题,对吗?

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!.");
  });
});

如何将 ui 从 app.post() 传递到存储?或者,如果您有更好的解决方案,我会洗耳恭听。

谢谢


最终解决方案

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!.");
  });

});

这个怎么样?

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

然后在 multer

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

filename