我正在将我的 NodeJS 项目迁移到 API Gateway,但我不知道如何从 Lambda 下载文件。
这是我本地 Node 项目的响应代码片段。
app.get('/downloadPDF', function (req, res) {
res.setHeader('Content-disposition', 'attachment; filename=test.pdf');
res.setHeader('Content-type', 'application/pdf');
var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);
var pdfDoc = printer.createPdfKitDocument(dd);
pdfDoc.pipe(res);
pdfDoc.end();
});
管道响应我能够取回PDF。
这是我使用无服务器的 lambda 函数的片段。
module.exports.createPDF = (event, context) => {
var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);
var pdfDoc = printer.createPdfKitDocument(dd);
pdfDoc.pipe(res);
pdfDoc.end();
}
这是我的 serverless.yml 中的端点
createPDF:
handler: functions.myFunction
events:
- http:
path: services/getPDF
method: get
response:
headers:
Content-Type: "'application/pdf'"
Content-disposition: "'attachment; filename=test.pdf'"
我不知道如何在 Lambda 中获取对响应对象的引用以进行管道传输。那可能吗?还有其他方法吗?
更新
我最终通过在 JSON 响应中返回 base64 编码的 PDF 二进制文件并在客户端解码来解决这个问题。注意:在响应映射模板中使用 base64 解码不起作用。
示例代码:
var buffers = [];
pdfDoc.on('data', buffers.push.bind(buffers));
pdfDoc.on('end', function () {
var bufCat = Buffer.concat(buffers);
var pdfBase64 = bufCat.toString('base64');
return cb(null,
{"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": pdfBase64});
});