Reputation: 706
I want to upload a image file (base64) on amazon S3 but i am continously getting this error :
I am building an IONIC app and my code is :
var reader = new FileReader();
reader.readAsDataURL(value);
reader.onloadend = function(e) {
console.log(this.result);
// AWS
AWS.config.update({
accessKeyId: $rootScope.config.access_key,
secretAccessKey: $rootScope.config.secret_key
});
AWS.config.region = 'us-west-2';
var bucket = new AWS.S3({ params: { Bucket: $rootScope.config.bucket } });
var params = {
Key: value.name,
ContentType: value.type,
Body: this.result,
ServerSideEncryption: 'AES256',
ACL: "public-read"
};
bucket.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
// alert(err.message);
console.log(JSON.stringify(err));
return false;
}
else {
// Success!
console.log('Upload Done');
}
})
.on('httpUploadProgress',function(progress) {
// Log Progress Information
console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
});
Where value contains a dataURI.
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA..... How to solve this problem ?
Upvotes: 0
Views: 107
Reputation: 491
I had to use a more permissive config to get it to work:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Upvotes: 0
Reputation: 3080
In your Amazon S3 account go to bucket "Properties" -> "Permissions" -> "Edit CORS Configuration"
Set:
<?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>Authorization</AllowedHeader>
<AllowedHeader>Content-Type</AllowedHeader>
<AllowedHeader>Origin</AllowedHeader>
</CORSRule>
</CORSConfiguration>
You can restrict the allowed origin to only your host (e.g. "http://www.example.com" in <AllowedOrigin>
instead of *
), but since your bucket is only writable with authentication anyway, this shouldn't be necessary.
Upvotes: 1