使用nodejs将文件上传到S3时出现格式问题

问题描述 投票:0回答:1

我从第三方 API 获取此类数据

%PDF-1.7 %���� 2093 0 obj <> endobj 2240 0 obj <>/Filter/FlateDecode/ID[(\204\240\33\17\372\324FC\221_B\326\226\7\374\206) (\204\240\33\17\372\324FC\221_B\326\226\7\374\206)]/Index[2093 148]/Info 2092 0 R/Length 164/Prev 1150275/Root 2094 0 R/Size 2241/Type/XRef/W[1 3 1]>> stream x�cbd```b`` �� ���d4�6`�D2��`�L.��������`R���LZ�E������S�`"�V!،�`v���dbgc����0�`?ƃH��`�<0�DJ�lg|2�q��?u�^�Qr������w�|&�g&��ŕ��� endstream endobj startxref 0 %%EOF 2094 0 obj <>/Metadata 1312 0 R/Pages 1566 0 R/StructTreeRoot 1569 0 R/Type/Catalog/ViewerPreferences 2140 0 R>> endobj 2238 0 obj <> stream

这是我想在 s3 上上传的 pdf 文件,这是代码

const response = await axios.get(url, options);
const file = { originalname: `${docName}.pdf`, buffer: response.data };
await this.s3Service.upload(file, `${S3_BASE_PATH.DOCS}/ENQ_${enquiryDocDto.enquiryId}`);

以及s3服务上的上传方法

async upload(file, basePath: string): Promise<string> {

    const fileName = this._getRandomFileName(file)
    const bucketFileKey = `${basePath}/${fileName}`;

    const params: AWS.S3.PutObjectRequest = {
      Bucket: this.bucketName,
      Key: bucketFileKey,
      Body: file.buffer
    };

    this.logger.log(`Uploading ${bucketFileKey}`);

    await this.s3.putObject(params).promise();
    this.logger.log(`Uploaded ${bucketFileKey}`);
    return bucketFileKey;
  }

从我获取此 pdf 数据的 api 在邮递员上工作,它返回相同的数据,并在保存邮递员的响应时创建一个有效的 pdf。

但通过代码无法正确上传

我什至尝试过像这样创建缓冲区

const buffer = Buffer.from(response.data, "utf-8")

甚至尝试过

"binary"
类型但没有运气。

在这种情况下,当我直接从我的nodejs上传时,相同的上传s3方法可以工作

Buffer
来了

所以我尝试将其转换为

Buffer
但转换显示它为
Uint8Array

更新1

const options = {
        headers: { accept: "*/*", authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/octet-stream' }
      };

我尝试删除内容类型,也接受,也更改接受申请人/pdf

甚至尝试过这个

fs.writeFileSync("A.pdf", Buffer.from(response.data));
      fs.writeFileSync("B.pdf", Buffer.from(response.data, "binary"));
      fs.writeFileSync("C.pdf", Buffer.from(response.data, "utf-8"));
      fs.writeFileSync("D.pdf", response.data);

还是同样的问题

node.js amazon-s3 axios
1个回答
0
投票

尝试将

responseType: 'arraybuffer'
添加到 axios 选项中:

const response = await axios.get(url, {responseType: 'arraybuffer'});

// file is now a buffer
const file = { originalname: `${docName}.pdf`, buffer: response.data };
© www.soinside.com 2019 - 2024. All rights reserved.