java 函数返回类型 动态_通过AWS API网关和Lambda函数返回动态内容类型

原来API网关不是问题 . 我的Lambda函数没有返回正确的 Headers .

为了处理二进制响应,我发现你需要将二进制支持内容类型设置为 */* (也就是所有内容),然后让你的Lambda函数返回属性 isBase64Encoded 设置为 true . base64编码并以此方式指示的响应将被解码并作为二进制提供,而其他请求将按原样返回 .

这是Lambda函数的简单Gist,它接受给定路径并从S3读取文件并通过API网关返回:

/**

* This is a simple AWS Lambda function that will look for a given file on S3 and return it

* passing along all of the headers of the S3 file. To make this available via a URL use

* API Gateway with an AWS Lambda Proxy Integration.

*

* Set the S3_REGION and S3_BUCKET global parameters in AWS Lambda

* Make sure the Lambda function is passed an object with `{ pathParameters : { proxy: 'path/to/file.jpg' } }` set

*/

var AWS = require('aws-sdk');

exports.handler = function( event, context, callback ) {

var region = process.env.S3_REGION;

var bucket = process.env.S3_BUCKET;

var key = decodeURI( event.pathParameters.proxy );

// Basic server response

/*

var response = {

statusCode: 200,

headers: {

'Content-Type': 'text/plain',

},

body: "Hello world!",

};

callback( null, response );

*/

// Fetch from S3

var s3 = new AWS.S3( Object.assign({ region: region }) );

return s3.makeUnauthenticatedRequest(

'getObject',

{ Bucket: bucket, Key: key },

function(err, data) {

if (err) {

return err;

}

var isBase64Encoded = false;

if ( data.ContentType.indexOf('image/') > -1 ) {

isBase64Encoded = true;

}

var encoding = '';

if ( isBase64Encoded ) {

encoding = 'base64'

}

var resp = {

statusCode: 200,

headers: {

'Content-Type': data.ContentType,

},

body: new Buffer(data.Body).toString(encoding),

isBase64Encoded: isBase64Encoded

};

callback(null, resp);

}

);

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值