简体   繁体   中英

Uploading multiple files with documents

I want to add multiple files with documents and it works, but I have multiple errors and all things are seen after reloading page. Here's my post route:

// @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))
    });
  }
});

And here's the warning/error(I get X errors, if I upload X files, and this rejection id:x is the order number of file):

(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)

And I suspect that problem is probably connected with that res.json(), which from what I studied should be used only once.

You can try like this:

// @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))
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM