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

时间:2017-12-29 00:16:04

标签: javascript node.js express multer

我使用shortid为每个上传的唯一ID,并为帖子处理程序进行过滤。

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

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

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

如何通过app.post()将ui传递给存储?或者,如果你有一个更好的解决方案,我会全力以赴。

谢谢

最终解决方案

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

});

1 个答案:

答案 0 :(得分:0)

这个怎么样?

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

然后在闷车

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

filename

相同