使用文档上传多个文件

Uploading multiple files with documents

我想添加多个带有文档的文件并且它可以工作,但是我有多个错误并且重新加载页面后所有内容都可以看到。 这是我的 post 路线:

// @route POST /upload
// @desc  Uploads file and object to DB
router.post('/', upload.any(), (req, res) => {
  if (req.files !== undefined) {
    console.log(req.files);
    req.files.map(({ id, filename }) => {
      const newGallery = new Gallery({
        files_id: id,
        image: '/api/gallery/image/' + filename,
        description: req.body.description,
        tripLocation: req.body.tripLocation,
      })
      newGallery.save().then(photo => res.json(photo))
    });
  }
});

这里是 warning/error(我收到 X 个错误,如果我上传 X 个文件,这个拒绝 id:x 是文件的订单号):

(node:7855) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client [0] at ServerResponse.setHeader (_http_outgoing.js:470:11) [0] at ServerResponse.header (/home/wiktor/MyApp/node_modules/express/lib/response.js:771:10) [0] at ServerResponse.send (/home/wiktor/MyApp/node_modules/express/lib/response.js:170:12) [0] at ServerResponse.json (/home/wiktor/MyApp/node_modules/express/lib/response.js:267:15) [0] at newGallery.save.then.photo (/home/wiktor/MyApp/routes/api/gallery.js:94:43) [0] at process._tickCallback (internal/process/next_tick.js:68:7) [0] (node:7855) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)

而且我怀疑问题可能与 res.json() 有关,根据我的研究,它应该只使用一次。

你可以这样试试:

// @route POST /upload
// @desc  Uploads file and object to DB
router.post('/', upload.any(), async (req, res, next) => {
  if (req.files !== undefined) {
    console.log(req.files);
    await Promise.all(req.files.map(({ id, filename }) => {
      const newGallery = new Gallery({
        files_id: id,
        image: '/api/gallery/image/' + filename,
        description: req.body.description,
        tripLocation: req.body.tripLocation,
      })
      return newGallery.save()
    })).then(data => res.json(data))
       .catch(err => next(err))
  }
});