![](/img/trans.png)
[英]How to extract binary data from multipart/form-data request? (Python) (multipart request base64 encoded by AWS API Gateway)
[英]How to create an AWS Lambda/API gateway python function that takes a pdf file as input using multipart/form-data?
我已經為此苦苦掙扎了一段時間。 我需要在 API 網關中創建一個資源,該資源鏈接到一個 lambda 函數,該函數將 pdf 文件作為作為多部分/表單數據 POST 請求發送的輸入。 為簡單起見,我現在只是返回文件。
當我嘗試使用以下 curl 調用 API 時,我收到來自 AWS 的內部服務器錯誤。 有沒有人成功地將 pdf 文件發送到 Lambda 而不必使用 S3 技巧(上傳到 S3)?
提前感謝大家的任何提示。
命令/文件:
卷曲
curl -vvv -X POST -H "Content-Type: multipart/form-data" -F "content=@file.pdf" https://...MYAPIHERE.../pdf
我目前正在使用無服務器和 python3。
以下是我的文件:
服務端.yaml
function:
pdf:
handler: handler.pdf
events:
- http:
path: /pdf
method: post
integration: lambda
request:
template:
application/json: "$input.json('$')"
response:
headers:
Content-Type: "'aplication/json'"
處理程序
def pdf(event, context):
pdf = event.get('content')
out = {'statusCode': 200,
'isBase64Encoded': False,
'headers': {"content-type": "application/json"},
'body': json.dumps({
'input': pdf,
'inputType': 'url',
#'tags': list(tags.keys()),
'error': None})}
return(out)
經過大量的谷歌搜索並在 AWS 支持團隊的幫助下,我終於設法解決了這個問題。
事實證明,API 網關會檢查傳入請求中的標頭:“Content-Type”或“Accept”,並將其與Binary Media Type的設置進行匹配,以決定將哪個有效負載視為二進制。 這意味着我們需要指定兩種內容類型(multipart/form-data、application/pdf)作為Binary media type 。
這可以通過使用做到這一點使用serveless無服務器- apigw二進制和添加這些到serverless.yaml:
plugins:
- serverless-apigw-binary
custom:
apigwBinary:
types: #list of mime-types
- 'multipart/form-data'
- 'application/pdf'
但是由於 lambda 需要來自 API 網關的application/json格式的有效負載,因此無法直接傳遞二進制數據。 因此,ContentHandling 的設置應設置為“CONVERT_TO_TEXT”。 在 yaml 文件中,這轉換為:
contentHandling: CONVERT_TO_TEXT
Kris Gohlson 在 serverless -thumbnail 上解決了最后一個問題。 謝謝你的克里斯。 我只是想知道你是怎么想到這個的...
無服務器.yaml
plugins:
- serverless-apigw-binary
custom:
apigwBinary:
types: #list of mime-types
- 'multipart/form-data'
- 'application/pdf'
function:
pdf:
handler: handler.pdf
events:
- http:
path: /pdf
method: post
integration: lambda
request:
contentHandling: CONVERT_TO_TEXT
passThrough: WHEN_NO_TEMPLATES
template:
application/pdf: "{'body': $input.json('$')}"
multipart/form-data: "{'body': $input.json('$')}"
response:
contentHandling: CONVERT_TO_BINARY
headers:
Content-Type: "'aplication/json'"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.