How to send a file as multipart/form-data from node.js when it is uploaded from client as multipart/form-data already?

Viewed 2093

I have a NodeJs/React application. The use case is to upload a file, get it scanned by a third party API and then if successful save the same. We cannot save file before scan is done.

We are uploading the file as multipart-formdata from react using a fetch method. Once file is received in Node.js to access the file and check for filesize and type we are using multer as below.

  router.post("/upload", upload.any("fieldname"), (req, res) => {
    scanFiles(req.files[0])
      .then((data) => {
        global.logger.info("scanned successfully.....");
        res.status(200);
      })
      .catch((err) => {
        global.logger.info("scan api ended with errors", err);
        res.status(400).send({ error: err.message })
      });
  });

Now the scan api expects us to send the file as multipart form data as well. In this scenario how to use the field received in req.files[0] to append to formData. I tried the below but its failing

const formData = new FormData();
try {
  formData.append("file", file, "sample_pdf");
} catch (err) {
  global.logger.error("Form data ended with errors", err);
}

I am getting an error while trying to do the same. It seems the second parameter to formData.append expects a file stream but instead getting file object from the req.files[0]. In this scenario do we need to convert the file data to a file stream?

1 Answers

formData.append expect file as Blob I don't understand type of req.files[0]

but if this file have method .arrayBuffer(), you can try it

file.arrayBuffer().then((array) => {
    formData.append('file', new Blob([array]), 'simple_pdf.pdf');
});
Related