【问题标题】:Unable to write file in proper format after reading from the S3 url using nodejs使用nodejs从S3 url读取后无法以正确的格式写入文件
【发布时间】:2022-12-18 12:05:08
【问题描述】:

在 axios 数据的帮助下从 S3 存储桶 url 读取后,我试图编写 excel 文件,但它不是可读格式。我想以上传数据的正确excel file format 格式写入数据。

下面是我的代码:

 axios({
            url: 'https://example.com/1666960010753_Me%20Data.xlsx',
            method: 'GET',
            responseType: 'blob',
        }).then((response) => {

            const ostream = fs.createWriteStream(`./${filename}`);
            ostream.write(response.data);
           
        });

有人让我知道我做错了什么。

【问题讨论】:

    标签: javascript node.js axios


    【解决方案1】:

    首先,您的 Excel 数据表现已公开。不知道这是否是故意的,但如果不是,请将其从您的代码示例中删除。


    现在的问题。

    您应该使用“arraybuffer”而不是“blob”作为响应类型。 This answer explains it really well why that is

    此外,您应该结束直播。这表明流已完成,没有数据应该并且可以再次写入流。

    为了完成它,您应该将写入流的编码设置为“二进制”。数组缓冲区是一个二进制缓冲区,当您知道要获取的数据时,最好的做法是设置文件的编码。


    对于您的代码,它看起来像这样:

    axios({
      url: 'https://<s3-domain>/<path-to-excel-file>.xlsx',
      method: 'GET',
      responseType: 'arraybuffer',
    }).then((response) => {
      const ostream = fs.createWriteStream(`./${filename}`, 'binary');
      ostream.pipe(response.data);
      ostream.end();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-18
      • 2019-08-11
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多