API网关似乎损坏或截断了base64编码的二进制数据

时间:2018-08-01 16:37:39

标签: amazon-web-services aws-lambda aws-api-gateway

我正在使用AWS API Gateway消耗图像文件以发送给Lambda函数。 POST很好地实现了Lambda函数,将二进制数据转换为base64字符串,但是当我尝试对该base64字符串进行解码并将其另存为图像时,无法对该图像进行解码。实际上,转换后返回的字符串小于图像本身,这使我认为出了点问题。我试过简单地返回提供给Lambda函数的字符串作为响应,并在本地对其进行解码,这也不起作用。

这是我的API网关方法的配置:

  "/photo/{photo_id}": {
  "x-amazon-apigateway-any-method": {
    "consumes": [
      "image/jpeg",
      "image/jpg"
    ],
    "produces": [
      "application/json",
      "image/jpg"
    ],
    "parameters": [
      {
        "name": "Content-Type",
        "in": "header",
        "required": false,
        "type": "string"
      },
      {
        "name": "Accept",
        "in": "header",
        "required": false,
        "type": "string"
      },
      {
        "name": "photo_id",
        "in": "path",
        "required": true,
        "type": "string"
      },
      {
        "in": "body",
        "name": "Empty",
        "required": true,
        "schema": {
          "$ref": "#/definitions/Empty"
        }
      },
      {
        "in": "body",
        "name": "Empty",
        "required": true,
        "schema": {
          "$ref": "#/definitions/Empty"
        }
      }
    ],
    "responses": {
      "200": {
        "description": "200 response",
        "schema": {
          "$ref": "#/definitions/Empty"
        }
      },
      "500": {
        "description": "500 response"
      }
    },
    "x-amazon-apigateway-integration": {
      "credentials": "redacted",
      "uri": "redacted",
      "responses": {
        "default": {
          "statusCode": "200"
        },
        ".*Error.*": {
          "statusCode": "500"
        }
      },
      "requestParameters": {
        "integration.request.header.Accept": "method.request.header.Accept",
        "integration.request.header.Content-Type": "method.request.header.Content-Type"
      },
      "requestTemplates": {
        "image/jpeg": "{\"photo\": \"$input.body\", \"photo_id\": \"$input.params('photo_id')\", \"app_id\": \"$input.params('x-app-id')\", \"httpMethod\": \"$context.httpMethod\"}",
        "image/jpg": "{\"photo\": \"$input.body\", \"photo_id\": \"$input.params('photo_id')\", \"app_id\": \"$input.params('x-app-id')\", \"httpMethod\": \"$context.httpMethod\"}"
      },
      "passthroughBehavior": "when_no_templates",
      "httpMethod": "POST",
      "contentHandling": "CONVERT_TO_TEXT",
      "type": "aws"
    }
  }
}

和简单的Lambda函数将字符串返回:

def lambda_handler(event, context):
  photo_string = event['photo']
  return photo_string

我用来测试实现的cURL命令:

curl -X POST https://execute-api.eu-central-1.amazonaws.com/prod/photo/new -H "Content-Type: image/jpg" -H "x-app-id:test" -d @IMG_1642.jpg

您知道为什么返回的base64会有所不同吗?

1 个答案:

答案 0 :(得分:0)

我知道了,我需要在cURL调用中使用--data-binary,而不仅仅是-d,它是--data-ascii的别名。现在工作正常。