2

我正在从 3rd-party API 获取 PDF。响应内容类型是application/octet-stream。此后,我将其上传到 S3,但是如果我去 S3 并下载新编写的文件,则内容不可见,页面为空白,在 Chromium 和 Adob​​e Acrobat 中查看。该文件也不是零字节并且具有正确的页数。

使用二进制编码给我一个最接近实际文件大小的文件大小。但它仍然不准确,它稍微小一些。

API 请求(使用request-promise模块):

import { get } from 'request-promise';

const payload = await get('someUrl').catch(handleError);

const buffer = Buffer.from(payload, 'binary');
const result = await new S3().upload({
  Body: buffer,
  Bucket: 'somebucket',
  ContentType: 'application/pdf',
  ContentEncoding: 'binary',
  Key: 'somefile.pdf'
}).promise();

此外,从 Postman 下载文件也会导致文件出现空白页。有人知道我在这里哪里出错了吗?

4

1 回答 1

1

正如评论中提到的@Micheal - sqlbot,下载是问题所在。我没有从 API 获得整个字节流。

改变const payload = await get('someUrl').catch(handleError);

import * as request from 'request'; // notice I've imported the base request lib 

let bufferArray = [];

request.get('someUrl')
.on('response', (res) => {

  res.on('data', (chunk) => {
    bufferArray = bufferArray.concat(Buffer.from(chunk)); //save response in a temp array for now
  });

  .on('end', () => {
    const dataBuffer = Buffer.concat(bufferArray); //this now contains all my data
    //send to s3
  });
});

注意:不建议使用request-promise库流式传输响应 - 在文档中进行了概述。我改用了基础request库。

https://github.com/request/request-promise#api-in-detail

于 2019-02-27T05:48:31.537 回答