如何在NodeJs环境中使用Multer上传和重命名文件

时间:2019-03-25 10:30:19

标签: javascript node.js file file-upload multer

我正在尝试在NodeJs环境中使用Multer上传多个文件:

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'my_uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, req.body.original_name)
  }
})

const upload = multer({
  storage: storage
})

app.post('/file_upload', upload.any(), function (req, res, next) {
  console.log('>>> \n\t' + JSON.stringify(req.files))
  res.json({
    success: true,
    message: 'Photo was updated !'
  })
})

我有一些包含文件的多部分数据:

console.log('>>> \n\t' + JSON.stringify(req.files))  

输出多部分数据:

[
   {
      "fieldname": "/storage/emulated/0/DCIM/.thumbnails/1535630435399.jpg",
      "originalname": "jpeg",
      "encoding": "binary",
      "mimetype": "application/octet-stream",
      "destination": "my_uploads/",
      "original_name": "1533906137379-d2019-03-25-13-16-26-g15.jpg",
      "path": "my_uploads/1533906137379-d2019-03-25-13-16-26-g15.jpg",
      "size": 29955
   },
   {
      "fieldname": "/storage/emulated/0/DCIM/.thumbnails/1535630444275.jpg",
      "originalname": "jpeg",
      "encoding": "binary",
      "mimetype": "application/octet-stream",
      "destination": "my_uploads/",
      "original_name": "1533906137379-d2019-03-25-13-16-26-g15.jpg",
      "path": "my_uploads/1533906137379-d2019-03-25-13-16-26-g15.jpg",
      "size": 48901
   }
]  

如您所见:

cb(null, req.body.original_name)  

我正尝试将文件重命名为包含在已发送的多部分数据中的 original_name

如何成功执行此操作?

谢谢大家。

0 个答案:

没有答案