如果我错过了一些简单的东西,提前道歉!我已经成功地通过AWS API Gateway从React将图像发送到AWS Lambda。我将其上传到同一个Lambda函数中的一个s3存储桶中。以下是React代码:
// 在APP中初始化状态
const [selectedImage, setSelectedImage] = useState();
// 输入
<input
accept="image/jpg, image/jpeg, image/png"
type="file"
onChange={imageChange}
/>
...
...
// 当文件字段更改时触发此函数
const imageChange = (e) => {
if (e.target.files && e.target.files.length > 0) {
setSelectedImage(e.target.files[0]);
}
};
...
...
// 当用户点击接受按钮时触发此函数
async function submitToBackend() {
// 这里的图像是jpg格式
setSelectedImage(e.target.files[0]);
const backendResponse = await fetch(awsapigatewayurl, {
method: "PUT",
headers: {
"Content-Type": "image/*",
},
body: selectedImage,
})
console.log(backendResponse)
}
在API Gateway上,我启用了Lambda代理转发,并启用了二进制图像格式,如下所示
Lambda代理设置
API Gateway二进制设置
现在这里是奇怪的部分...至少对我来说.. 在我的Python后端代码中,我有:
def lambda_handler(event, context):
key = 'test.jpg'
data = event['body']
decoded_data = base64.b64decode(data)
image_filelike = io.BytesIO(decoded_data)
# 创建日期文件夹,如果已经创建则忽略
current_date = str(datetime.date.today())
s3_client.put_object(Bucket=BUCKET, Key=(current_date + '/'))
# 将图像上传到S3
s3_client.upload_fileobj(Bucket=BUCKET,
Key='%s/%s' % (current_date, key),
Fileobj=image_filelike)
但你看我必须这样做:
decoded_data = base64.b64decode(data)
我以为我疯了,所以我进入了Postman,复制了curl命令,并修改它以从我的命令提示符发送二进制数据,如下所示:
curl --location --request PUT "apigatewayurl" \ --header "Content-Type: image/jpeg" \ --data-binary "@/Users/user/Documents/IMG_7138.jpg"
它运行得很好。
我应该对数据进行base64编码,但从我看到的API Gateway或链中的某些东西已经这样做了。请告诉我是否做错了,并且是否应该以更好的方式进行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
好的,看一下这篇文章 https://aws.amazon.com/blogs/compute/handling-binary-data-using-amazon-api-gateway-http-apis/,看起来编码是根据"content-type"头来确定的。您可以通过在Lambda函数中使用以下代码并查看CloudWatch日志中的结果来查看Python后端代码:
print("isBase64Encoded: %s" % event['isBase64Encoded'])
我会在这里保留代码和解决方案,以便其他人需要帮助时可以使用。