在AWS Lambda中使用Multer从MongoDB渲染PDF失败问题排查
AWS Lambda部署后PDF渲染空白问题解决
问题描述
React应用通过Multer从MongoDB读取并渲染PDF,本地Express环境完全正常,但切换到AWS Lambda托管的API后,仅能显示PDF文件名,渲染出空白PDF。不想使用S3或其他AWS存储服务,询问是否需要为AWS Lambda安装额外依赖。
相关代码
简历Schema
const resumeSchema = new mongoose.Schema({ name: String, data: Buffer, contentType: String, userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, });
后端响应代码(本地Express)
res.setHeader("Content-Type", matchedResume.contentType); res.setHeader( "Content-Disposition", `inline; filename="${matchedResume.name}"` ); res.status(200).send(matchedResume.data);
React渲染代码
onClick={() => { const config = { method: "get", headers: { Authorization: `Bearer ${token}`, }, url: `http://localhost:8257/user/resume/resumes?rId=${props.resume.rId}`, responseType: "blob", }; axios(config) .then((res) => { const blobUrl = window.URL.createObjectURL( new Blob([res.data], { type: "application/pdf" }) ); // Open the blob URL in a new tab window.open(blobUrl, "_blank"); }) .catch((error) => console.log(error)); }}
原因分析
本地Express和AWS Lambda的响应处理逻辑存在核心差异:
- Express直接发送Buffer数据时,HTTP协议会原生传输二进制内容,前端可正确解析。
- AWS Lambda搭配API Gateway时,默认会对非文本响应进行Base64编码,若未配置对应二进制媒体类型,API Gateway会错误解析数据,导致前端拿到损坏的二进制内容,最终渲染空白PDF。
解决方案
不需要额外安装依赖,只需调整API Gateway配置和Lambda响应格式:
1. 配置API Gateway支持二进制媒体类型
- 登录AWS控制台,进入API Gateway,选择目标API。
- 切换到设置标签,在二进制媒体类型中添加
application/pdf。 - 点击保存,重新部署API到对应阶段。
2. 修改Lambda响应格式
如果后端通过Lambda直接处理请求,需将Buffer转换为Base64字符串,并设置isBase64Encoded: true:
// Lambda函数中的响应逻辑 const matchedResume = await Resume.findById(rId); return { statusCode: 200, headers: { 'Content-Type': matchedResume.contentType, 'Content-Disposition': `inline; filename="${matchedResume.name}"` }, body: matchedResume.data.toString('base64'), isBase64Encoded: true };
若使用Express框架部署在Lambda上(如通过Serverless),多数框架会自动处理响应格式转换,若仍有问题,可手动调整上述响应逻辑。
3. 前端验证
保持现有responseType: "blob"配置不变,API Gateway会自动将Base64解码为二进制Blob,前端可直接用于创建URL并渲染。
内容的提问来源于stack exchange,提问作者Syed Faraz Hasan
相关产品推荐
相关产品推荐

