You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

API Gateway无法返回二进制图片求助(客户端无法设置Accept头)

问题描述

需求是让Lambda处理图片后返回实际二进制图片(而非链接)。当前情况:

  • 请求携带Accept: image/*头时,API可正常返回图片
  • 某移动端客户端因框架限制无法修改Accept头,导致API Gateway返回的不是正确的二进制图片
  • Lambda返回Base64编码的图片,响应结构正确(isBase64Encoded设为trueContent-Type为对应图片类型)
  • API Gateway的Binary media types已配置image/*及各类具体图片格式,均无效

Lambda返回示例:

{
  "statusCode": 200,
  "headers": {
    "Cache-Control": "public, max-age=31536000",
    "Content-Type": "image/jpeg",
    "X-Content-Transfer-Encoding": "binary",
    "X-Content-Type": "image/jpeg",
    "X-Encoded-Size": "10720",
    "X-Image-Size": "8040"
  },
  "multiValueHeaders": null,
  "body": "/9j/2wCEAAUDBAQEAwUEBAQFBQUGBwwIBwcH.........",
  "isBase64Encoded": true
}

Lambda返回逻辑(Golang):

return events.APIGatewayProxyResponse{
        StatusCode: http.StatusOK,
        Body:       base64.StdEncoding.EncodeToString(img.Content),
        Headers: map[string]string{
            "Content-Type":                img.ContentType,
            "Cache-Control":               "public, max-age=31536000",
            "X-Content-Transfer-Encoding": "binary",
            "X-Image-Size":                fmt.Sprintf("%d", len(img.Content)),
            "X-Encoded-Size":              fmt.Sprintf("%d", len(base64.StdEncoding.EncodeToString(img.Content))),
            "X-Content-Type":              img.ContentType,
        },
        IsBase64Encoded: true,
    }
解决方案

1. 开启API Gateway强制二进制响应配置(REST API)

API Gateway默认依赖请求的Accept头判断是否返回二进制,开启强制选项后,将仅依据响应的Content-Type处理:

  • 进入API Gateway控制台,打开目标API的Settings页面
  • Binary Media Types区域,启用Force Content-Type to be treated as binary(部分控制台翻译为“强制将Content-Type视为二进制”)
  • 保存配置后重新部署API

2. HTTP API(v2)适配设置

如果使用API Gateway v2(HTTP API):

  • 在API的Settings页面,确认Payload format version设置为2.0(1.0版本依赖Accept头判断二进制)
  • 确保Binary media types已添加image/*或具体图片类型

3. 检查集成响应配置

  • 进入Lambda集成的Integration Response设置,确认没有对Content-Type做额外覆盖或转换
  • 确保Method Response中配置的Content-Type与Lambda返回的一致(如image/jpeg

4. 验证Lambda返回字段

  • 确认Lambda日志中IsBase64Encoded字段始终为true,未被其他逻辑修改
  • 确保返回的Content-Type是标准图片MIME类型(如image/jpegimage/png),而非自定义值

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

火山引擎 最新活动