【发布时间】:2020-01-15 20:07:27
【问题描述】:
我生成了一个预签名 URL,用于通过 Python 支持的 API 将文件上传到 AWS S3。一旦用户在浏览器中选择文件(见下文),这部分就会接收文件名信息,并返回带有基本 URL 和字段的 JSON 有效负载(见下文)。
import logging
import boto3
from botocore.exceptions import ClientError
def create_presigned_post(bucket_name, object_name,
fields=None, conditions=None, expiration=3600):
# Generate a presigned S3 POST URL
s3_client = boto3.client('s3')
try:
response = s3_client.generate_presigned_post(bucket_name,
object_name,
Fields=fields,
Conditions=conditions,
ExpiresIn=expiration)
except ClientError as e:
logging.error(e)
return None
# The response contains the presigned URL and required fields
return response
这是我从这个函数得到的 JSON 响应。 (我更改/缩写了一些值,但你明白了。)
{
"url": "https://s3.us-east-2.amazonaws.com/my_bucket_name",
"fields": {
"key": "some.txt",
"AWSAccessKeyId": "ASI...",
"x-amz-security-token": "Ag9o...",
"policy": "eyJ...=",
"signature": "jn...="
}
}
这是我用来上传文件的 HTML 表单。我有一些原始的 Javascript 可以跟踪表单的更改,并在更改时更新表单的 URL_VALUE 和每个表单项的 VALUE(例如文件选择)。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!-- Copy the 'url' value returned by S3Client.generate_presigned_post() -->
<form action="URL_VALUE" method="post" enctype="multipart/form-data">
<!-- Copy the 'fields' key:values returned by S3Client.generate_presigned_post() -->
<input type="hidden" name="key" value="VALUE" />
<input type="hidden" name="AWSAccessKeyId" value="VALUE" />
<input type="hidden" name="policy" value="VALUE" />
<input type="hidden" name="signature" value="VALUE" />
File:
<input type="file" name="file" /> <br />
<input type="submit" name="submit" value="Upload to Amazon S3" />
</form>
</body>
</html>
这个 HTML 表单本身可以正常工作,但我尝试添加一些 Javascript(vanilla 和 JQuery),所以我可以跟踪文件进度并禁用表单输入,直到上传完成。
我无法让 Javascript 工作!!!
我已经尝试了很多例子(同样,vanilla JS 和 JQuery)。
最近有没有人实现过这个并且可以提供帮助?
【问题讨论】:
-
我收到的错误信息多种多样:
Forbidden、Access Denied、Bad Request、MalformedPOSTRequest....主要是 403 和 412 状态码
标签: javascript python amazon-web-services amazon-s3