【问题标题】:Forward uploaded file from a service to another service将上传的文件从一个服务转发到另一个服务
【发布时间】:2021-10-14 18:28:48
【问题描述】:

我正在尝试使用 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);
})

【问题讨论】:

    标签: amazon-web-services rest express amazon-s3 multer


    【解决方案1】:

    我找到了一个解决方案,我在这里发布给那些有同样问题的人。

    在节点上安装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);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 2013-08-17
      • 2022-01-15
      • 2011-11-05
      • 1970-01-01
      • 2020-04-25
      相关资源
      最近更新 更多