You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Serverless与AWS无法处理二进制文件求助(最简代码场景)

问题:Serverless端点返回的PDF文件损坏(仅489字节乱码)

我搭建了一个极简的Serverless仓库,用于在AWS创建接收PDF并返回的端点,作为学习二进制文件处理的测试用例。

serverless.yml 配置

service: sls-pdf-service

provider:
  name: aws
  runtime: nodejs18.x
  memorySize: 256
  timeout: 10

functions:
  upload:
    handler: handler.upload
    events:
      - http:
          path: upload
          method: post
          cors: true

plugins:
  - serverless-apigw-binary
  - serverless-offline

custom:
  apigwBinary:
    types:
      - "application/pdf"

handler.js 代码

module.exports.upload = async (event) => {
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/pdf',
    },
    body: event.body, // 直接返回上传的PDF
    isBase64Encoded: true,
  };
};

package.json 配置

{
  "name": "sls-pdf-echo",
  "version": "1.0.0",
  "description": "",
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "serverless-apigw-binary": "^0.4.4",
    "serverless-offline": "^12.0.4"
  }
}

本地运行与调用方式

  • 本地启动命令:sls offline
  • curl调用命令:
curl -X POST -H "Content-Type: application/pdf" --data-binary "@4614fb56-335d-4985-bac6-7996af859297.pdf" http://localhost:3000/dev/upload -o out.pdf

问题描述

上传的PDF大小为1.3MB,但返回的文件仅489字节且为乱码。

更新1:我希望直接上传二进制PDF,而非Base64编码的文件。


解决方案

问题根源是serverless-offline本地运行时对二进制数据的处理逻辑与AWS线上环境不一致,默认会将二进制请求体解析为UTF-8字符串,导致数据损坏。按以下步骤修复:

1. 更新serverless.yml配置

添加serverless-offline的二进制类型支持,确保它能正确识别PDF格式:

custom:
  apigwBinary:
    types:
      - "application/pdf"
  serverless-offline:
    binary:
      types:
        - "application/pdf"

2. 修改handler逻辑

区分本地与线上环境的body处理:本地环境下需要将被错误解析的字符串重新编码为Base64,线上环境直接使用原始body即可:

module.exports.upload = async (event) => {
  let body = event.body;
  
  // 本地运行时,修复二进制数据编码问题
  if (process.env.IS_OFFLINE) {
    body = Buffer.from(event.body, 'binary').toString('base64');
  }

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'inline; filename="out.pdf"' // 可选:指定返回文件名称
    },
    body: body,
    isBase64Encoded: true,
  };
};

3. 重启本地服务

停止当前sls offline进程,重新执行sls offline启动服务。

4. 验证修复

再次使用原curl命令调用端点,返回的out.pdf应与原文件大小一致,且能正常打开。


内容的提问来源于stack exchange,提问作者Mike Hogan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:43:18