将上传的文件从一个服务转发到另一个服务

Forward uploaded file from a service to another service

我正在尝试使用 ExpressJS 创建一个 REST API 接受图像并将其传递给另一个服务(使用 POST 请求),该服务负责执行一些操作(调整大小等..)并存储到 AWS S3 中。我知道可以直接使用 Lambda 函数轻松完成相同的解决方案,但我有 K8s,我想让它物有所值。

除了将图像转发到第二个服务的服务外,所有组件都已在工作。

我在网上找到的想法是使用流,但我遇到了异常Error: Expected a stream at Object.getStream [as default]

我该如何解决?是正确的做法还是有更好的解决方案可以达到相同的结果?

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

我post在这里找到了一个解决方案,供遇到同样问题的人使用。

在节点上安装 form-data

yarn add form-data

然后在你的控制器中:

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