AWS:使用Lambda和API网关将空白文档上传到S3存储桶

时间:2019-01-10 06:36:39

标签: pdf amazon-s3 aws-lambda aws-api-gateway busboy

我正在尝试下载在S3存储桶中上传的 PDF 文件,该文件会通过 Lambda 函数和 API网关 POST < / strong>请求,但显示为空白,但对于其他文件(例如.txt),它运行正常。

API网关

/first-endpoint
 POST

集成请求类型为启用了代理集成的Lambda。 (已启用CORS)

AWS Lambda

const busboy = require('busboy');
const AWS = require('aws-sdk')
const s3 = new AWS.S3();

const headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'OPTIONS, POST',
  'Access-Control-Allow-Headers': 'Content-Type'
};

function handler(event, context, cb) {
  let contentType = event.headers['Content-Type'] || event.headers['content-type'];
  console.log('contentType', contentType)
  let bb = new busboy({ headers: { 'content-type': contentType } });

  bb.on('file', function (fieldname, file, filename, encoding, mimetype) {
    console.log('File [%s]: filename=%j; encoding=%j; mimetype=%j', fieldname, filename, encoding, mimetype);
    let params = { Bucket: 'test-api-dev-uploads', Key: filename, Body: file, ContentType: mimetype }

    s3.upload(params, function (err, resp) {
      console.log('resp >> ', resp);
      // console.log('Successfully uploaded package.');
         cb(null, { statusCode: 200, body: res.Key, headers });
    });
  })
    .on('field', (fieldname, val) => console.log('Field [%s]: value: %j', fieldname, val))
    .on('finish', () => {
      //  context.succeed({ statusCode: 200, body: 'all done', headers });
    })
    .on('error', err => {
      console.log('failed', err);
      //     context.fail({ statusCode: 500, body: err, headers });
      cb(null, { statusCode: 500, body: err, headers });
    });

  bb.end(event.body);
}

module.exports.hello = handler;

使用邮递员进行测试

POST请求:https://test-api.amazonaws.com/dev/first-endpoint

HEADERS Content-type: application/json

身体:表单数据

CV:(File): PDF file or docx

我没有收到任何错误,该pdf文件已在S3中上传,但是当我尝试下载并查看该文件时,它没有任何内容,即空白PDF / docx文件已损坏。

我尝试了其他解决方案,例如(尝试在API Gateway中启用二进制媒体)

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html

API网关的新功能,请建议我是否缺少API网关或Lambda函数中的任何内容?

0 个答案:

没有答案