我试图创建一个AWS Lambda函数与函数URL。该函数应接受文件(图像)上传沿着一些字段,如名称,日期和文本。
我从REACTJS中的前端发送请求:
export async function postFormData(url, form) {
const response = await axios({
method: "post",
url,
data: form,
headers: {
"Content-Type": "multipart/form-data",
},
})
return response.data
}
我也使用postman来测试API。但是,我无法解析lambda函数中的字段,我一直得到下面的错误,我猜这意味着主体没有正确形成?但我使用postman发送它,所以我不知道我做错了什么
ImproperBodyPartContentException: content does not contain CR-LF-CR-LF
我的AWS Lambda python3代码:
import json
import requests
from requests_toolbelt.multipart import decoder
def lambda_handler(event, context):
# get the request body and headers
body = event['body']
headers = event['headers']
# decode the multipart/form-data request
data = decoder.MultipartDecoder(body.encode(), headers['content-type'])
# iterate over the parts of the request
for part in data.parts:
# check if the part is a file
if part.headers[b'content-disposition'].startswith(b'form-data; name="file"; filename='):
# get the filename and content type of the file
filename = part.headers[b'content-disposition'].decode('utf-8').split('"')[3]
content_type = part.headers[b'content-type'].decode('utf-8')
# write the file content to disk or do something else with it
with open(filename, 'wb') as f:
f.write(part.content)
# if the part is not a file, print its content
else:
print(part.content.decode('utf-8'))
# create the response
response = {
'statusCode': 200,
'body': json.dumps({'message': 'Request processed successfully'})
}
return response
我只允许使用requests和requests toolbelt,所以如果你能给我一个只使用这两个库的解决方案,我将不胜感激。
总之,我只想使用AWS Lambda创建一个python API,它接受一些字符串数据,如名称,日期和文本以及图像文件。我想然后将图像文件保存为/tmp目录中的.png。
1条答案
按热度按时间toiithl61#
我想明白了: