我非常努力地在我的Django项目中实现this tutorial,但是没有成功。我认为我用来签署帖子的功能无法正常工作。 这是我的功能:
def sign_s3(request,*args, **kwargs):
S3_BUCKET = getattr(settings, 'FILEMANAGER_AWS_S3_BUCKET_NAME')
file_name = request.GET.get('file_name')
file_type = request.GET.get('file_type')
s3 = boto3.client('s3',
config = S3ClientCfg(signature_version = 's3v4'),
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
)
# s3 = get_aws_s3_client()
presigned_post = s3.generate_presigned_post(
Bucket = S3_BUCKET,
Key = file_name,
Fields = {"acl": "public-read", "Content-Type": file_type},
Conditions = [
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn = 3600
)
response_dict = {
'data': presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name)
}
mimetype = 'application/json'
return HttpResponse(json.dumps(response_dict), mimetype)
实际上,当我看着Web控制台时,我看到了:
Cross-Origin Request Blocked. (Reason: CORS request did not succeed)
答案 0 :(得分:1)
实际上我发现了问题所在。 在我的签名中,我提到该URL将在3600秒后过期。 您也必须在CORS中发出信号。
我的Bucket CORS应该像下面这样:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3600</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
答案 1 :(得分:0)
检查S3存储桶的CORS配置,可以在AWS控制台的S3存储桶的权限选项卡中找到CORS配置。
您可能会看到默认值:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
您需要对其进行更新,以允许您的网站(www.example.com)进行POST / PUT: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTcors.html
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
<CORSRule>
<AllowedOrigin>http://www.example.com</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>