问题
I am trying to download an image from S3. But I got error CORS.
What I have done:
-Setup CORS configuration for S3 bucket:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<ExposeHeader>Accept-Ranges</ExposeHeader>
<ExposeHeader>Content-Range</ExposeHeader>
<ExposeHeader>Content-Encoding</ExposeHeader>
<ExposeHeader>Content-Length</ExposeHeader>
<ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
-I uploaded an image using AWS console
-load image in html:
<div id="my-node">
<img id="image" src="path/to/s3/bucket/image.png" class="img-responsive"/>
</div>
-To download image, I use https://github.com/tsayen/dom-to-image to download
domtoimage.toBlob(document.getElementById('my-node'))
.then(function (blob) {
window.saveAs(blob, 'my-node.png');
});
Result: I received error
XMLHttpRequest cannot load path/to/s3/bucket/image.png. No 'Access-Control-Allow-Origin' header is present on the requested resource.
I inspected the image, the response header not including Access-Control-Allow-Origin (it seems S3 didn't include CORS configuration in response)
Accept-Ranges:bytes
Content-Length:124824
Content-Type:image/png
Date:Mon, 24 Apr 2017 17:27:48 GMT
ETag:"xxxxxxxx00000000"
Last-Modified:Mon, 24 Apr 2017 17:18:53 GMT
Server:AmazonS3
x-amz-id-2:xxxxxxxxxxxxxxxxx
x-amz-request-id:xxxxxxxxxxxx
Very appreciated for any suggestion or advice
回答1:
Your bucket policy needs to grant at least s3:GetBucketCORS
to public users, e.g.:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetBucketCORS"
],
"Resource": [
"arn:aws:s3:::mybucketname"
]
}
]
}
来源:https://stackoverflow.com/questions/43594753/aws-s3-bucket-cors-configuration