带有Axios的无服务器Api网关代理Lambda可以服务二进制文件(PDF)?

时间:2018-07-29 16:18:13

标签: pdf download binary axios aws-api-gateway

我正在使用无服务器和axios来“传递”由 stampery api,它需要凭据,我不想保存客户端。

原则上,我从 axios 获取PDF作为 arraybuffer ,将 arraybuffer 转换为 buffer ,然后我用它来创建API Gateway二进制处理所需的 base64 字符串,可以通过在回调响应对象中包含isBase64Encoded: true属性来“激活”该字符串。

以下代码产生一个空的PDF:

const axios = require('axios');

const stamperyClientId = 'xxx';
const stamperySecret = 'xxx';

const stampery = axios.create({
  baseURL: 'https://api-prod.stampery.com',
  auth: {
    username: stamperyClientId,
    password: stamperySecret
  }
});

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    headers: {
      'Content-Type' : 'application/pdf',
      'Content-Disposition': 'inline; filename="certificate.pdf"'
    },
    isBase64Encoded: true
  };

  stampery.get(`/stamps/5b2a612680e0190004bcccc8.pdf`, {
    responseType: 'arrayBuffer',
  })
    .then(res => {
      const buffer = Buffer.from(res.data)
      const base64Str = buffer.toString('base64')
      response.body = base64Str
      callback(null, response);
    })
};

通过以下方式检索PDF:“ curl https://xxx.execute-api.eu-west-1.amazonaws.com/dev/certificate -o my.pdf -H“接受:应用程序/ pdf”

我用fileReadSync测试了设置,结果很好:

module.exports.hello = (event, context, callback) => {
  const content = fs.readFileSync("data/sample.pdf");

  const response = {
    statusCode: 200,
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": "inline; filename=\"sample.pdf\""
    },
    body: content.toString("base64"),
    isBase64Encoded: true
  };

  return callback(null, response);
};

我想念什么?这是将 axios数组缓冲区转换为 base64 字符串的正确方法吗?

P.S。我的 serverless.yml 通过以下方式给出:

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: certificate.pdf
          method: get
    package:
      include:
        - data/sample.pdf

resources:
  Resources:
    ApiGatewayRestApi:
      Type: AWS::ApiGateway::RestApi
      Properties:
        Name: dev-stamper
        BinaryMediaTypes:
          - "application/pdf" # or whichever ones you need

我已经想到了必需的二进制媒体类型

1 个答案:

答案 0 :(得分:1)

好吧...错误是一个简单的错字。我在驼峰式 arrayBuffer 中编写了 arraybuffer ,所以Axios返回了一个字符串而不是arraybuffer。

更改此行:

 stampery.get(`/stamps/5b2a612680e0190004bcccc8.pdf`, {
    responseType: 'arrayBuffer',
  })

 stampery.get(`/stamps/5b2a612680e0190004bcccc8.pdf`, {
    responseType: 'arraybuffer',
  })

一切都变得迷人...