Forward uploaded file from a service to another service

Issue

I’m trying to create a REST API with ExpressJS that accept an image and pass it to another service (with a POST request) which is in charge to perform some operations (resize, etc..) and store into an AWS S3. I know that the same solution can be easily done with a Lambda Function directly but I have a K8s and I want to make worth it.

All components are already working with the exception of the service that forward the image to the second service.

The idea that I’ve found on internet is using a stream, but I got the exception Error: Expected a stream at Object.getStream [as default]

How can I solve that? Is the right practice or there is a better solution to achieve the same result?

const headers = req.headers;
const files: any = req.files

const filename = files[0].originalname;
const buffer = await getStream(files[0].stream)
const formFile = new FormData();
formFile.append('image', buffer, filename);

headers['Content-Type'] = 'multipart/form-data';
axios.post("http://localhost:1401/content/image/test/upload/", formFile, {
            headers: headers,
        })
        .catch((error) => {
          const { status, data } = error.response;
          res.status(status).send(data);
})

Solution

I’ve found a solution that I post here for those who’ll have the same problem.

Install form-data on node:

yarn add form-data

Then in your controller:

const headers = req.headers;
const files: any = req.files
const formFile = new FormData();

files.forEach((file: any) => {
 const filename = file.originalname;
 const buffer = file.buffer
 formFile.append('image', buffer, filename);
})
// set the correct header otherwise it won't work
headers["content-type"] = `multipart/form-data;  boundary=${formFile.getBoundary()}`

// now you can send the image to the second service
axios.post("http://localhost:1401/content/image/test/upload/", formFile, {
headers: headers,
})
.then((r : any) => {

  res.sendStatus(r.status).end()

})
.catch((error) => {
  const { status, data } = error.response;
  res.status(status).send(data);
})

Answered By – Vito V

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published