代码之家  ›  专栏  ›  技术社区  ›  Sunil Garg

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

  •  0
  • Sunil Garg  · 技术社区  · 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,它可以在postman上运行,并且返回相同的数据,在保存postman的响应时,它会创建一个有效的pdf。

    但通过代码上传不正确

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

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

    甚至尝试过 "binary" 类型,但运气不佳。

    在这种情况下,当我直接从nodejs上传时,同样的upload s3方法也适用 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);
    

    还是同样的问题

    1 回复  |  直到 1 年前
        1
  •  1
  •   traynor    1 年前

    尝试添加 responseType: 'arraybuffer' 到axios选项:

    const response = await axios.get(url, {responseType: 'arraybuffer', ...options});
    
    // file is now a buffer
    const file = { originalname: `${docName}.pdf`, buffer: response.data };