Reputation: 167
I am trying to upload image to Amazon S3 in an Ajax call but getting error like:
XmlHttpRequest cannot load https://bucketname.s3.amazonaws.com/. No 'Access-Control-
Allow_Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
My JavaScript is like this:
var xmlhttp = XmlHttpRequesr();
var file = document.getElementById('file').files[0];
var fd = new FormData();
var key = "events/" + (new Date).getTime() + '-' + file.name;
POLICY_JSON = {"expiration": "20020-01-01T00:00:00Z","conditions": [ {"bucket": "s3-bucket"},
["starts-with", "$key", ""], {"acl": "private"},{"success_action_redirect": "LOCALHOST"},
["starts-with", "$Content-Type", ""], ["content-length-range", 0, 1048576] ] };
var secret = this.get('key');
var policyBase64 = window.btoa(JSON.stringify(POLICY_JSON));
console.log ( policyBase64 );
var signature = b64_hmac_sha1(secret, policyBase64);
b64_hmac_sha1(secret, policyBase64);
fd.append('key', 'uploads/${filename}');
fd.append('acl', 'private');
fd.append('Content-Type', file.type);
fd.append('AWSAccessKeyId', key);
fd.append('policy', policyBase64);
fd.append('signature',signature);
fd.append("file",file); xmlhttp.open('POST', Url, true); xmlhttp.send(fd); }
Can anyone help me solve this problem?
Upvotes: 2
Views: 627
Reputation: 1365
Hope you've gotten somewhere with this. If not I can offer a little help. I'm just starting to mess with Amazon S3 but it seams to me that you need to set your access control settings.
https://console.aws.amazon.com/s3/home?region=us-east-1
Then click on your bucket. Then click on Properties.
You have to set up the bucket policy and the CORS policy.
I started by setting the bucket policy to admin and that allowed my uploads to work. Then figure out the minimum you need to do what you want to do so you're not leaving the gate open.
CORS policy is important too. I fear mine is too loose, not sure. But anyway it works:
<?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>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Upvotes: 1