Amazon Lambda - 返回 docx 文件 - Node.js

Tom*_*ula 4 docx amazon-s3 amazon-web-services node.js aws-lambda

我正在尝试将我的 Node.js 应用程序从Google Cloud Functions迁移到 Amazon Lambda。应用程序从 Amazon S3 加载 docx 文件,对其进行处理并返回该 docx 文件。但是我被困在文件返回的过程中。在 Google Cloud Platform 中,我可以这样做:

module.exports = function(customENV){ return function(req, res) {
    new AWS.S3().getObject({ Bucket: aws_bucket, Key: aws_file }, function(err, data) {
        if(!err) { 
            res.set('Access-Control-Allow-Origin', "*");
            res.set('Access-Control-Allow-Methods', 'GET, POST');
            res.set('Content-Disposition', `inline; filename="rename.docx"`);

            res.type('docx');
            res.status(200);

            res.end(data.Body, 'binary');
        }
    });
}};
Run Code Online (Sandbox Code Playgroud)

在 Amazon Lambda 中,我复制了这样的解决方案:

exports.handler = function(event, context, callback) {
    new AWS.S3().getObject({ Bucket: aws_bucket, Key: aws_file }, function(err, data) {
        if(!err) {
            var response = {
                statusCode: 200,
                headers: {
                    'Access-Control-Allow-Origin': "*",
                    'Access-Control-Allow-Methods': 'GET, POST',
                    'Content-type' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'Content-Disposition': 'inline; filename="rename.docx"'
                },
                isBase64Encoded: true,
                body: data.Body,
            };
            
            callback(null, response);
        }
    });
};

Run Code Online (Sandbox Code Playgroud)

作为 API 网关,我将 LAMBDA_PROXY 与任何方法一起使用。模型/响应/映射都处于“默认”状态。然而,我得到的唯一回应是“内部服务器错误”。在 CloudWatch 日志中,我还看到“由于配置错误执行失败:无法对正文进行 base64 解码”。

我尝试复制各种解决方案和/或 API 网关的不同配置,但没有成功。可能我只是不了解亚马逊的 API 网关,因此我不知道如何正确配置它。

也许正如日志所说,它也可能是数据转换,但我尝试了像toString("base64")这样的转换,也没有成功。

任何想法我应该怎么做才能使这个最小的解决方案起作用?谢谢!

tho*_*ace 6

如果您将响应更改为:

        var response = {
            statusCode: 200,
            headers: {
                'Access-Control-Allow-Origin': "*",
                'Access-Control-Allow-Methods': 'GET, POST',
                'Content-type' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'Content-Disposition': 'inline; filename="rename.docx"'
            },
            isBase64Encoded: true,
            body: Buffer.from(data.Body).toString('base64'),
        };
Run Code Online (Sandbox Code Playgroud)

这应该可以克服您的Unable to base64 decode the body错误(如果没有,您能否记录该response对象以确认您的 lambda 成功返回并且主体base64 字符串)。

但是,您还需要将二进制媒体类型添加到网关部署中,否则当您发出请求时,您的响应将是 base64 字符串而不是二进制。需要点击几下(完整文档):

  • 在主导航面板中选定的 API 下,选择设置。
  • 在设置窗格中,选择二进制媒体类型部分中的添加二进制媒体类型。
  • 在输入文本字段中键入所需的媒体类型,例如 image/png。如果需要,请重复此步骤以添加更多媒体类型。