I have written code for uploading image to amazon s3 using using angular js from browser directly. For that I am using the library aws-sdk.js . I have a function 'upload' in which I assign the credentials and the params, and the file. While uploading , I get the below error
*No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access*.
My CORS configuration
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>http://*</AllowedOrigin>
<AllowedOrigin>https://*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
<ExposeHeader>x-amz-request-id</ExposeHeader>
<ExposeHeader>x-amz-id-2</ExposeHeader>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
My controller function
function _upload($files) {
$scope.file = $files[0];
$scope.creds = {
accessKeyId: '...',
secretAccessKey: '...',
region: 'us-west-2',
bucket: 'sabari-test'
};
var bucket = new AWS.S3({
region: 'us-west-2',
credentials: new AWS.Credentials($scope.creds.accessKeyId, $scope.creds.secretAccessKey)
});
if ($scope.file) {
// Perform File Size Check First
var fileSize = Math.round(parseInt($scope.file.size));
if (fileSize > $scope.sizeLimit) {
console.log('Sorry, your attachment is too big.');
return false;
}
// Prepend Unique String To Prevent Overwrites
var uniqueFileName = 'hai' + '-' + $scope.file.name;
var params = {
Bucket: $scope.creds.bucket,
Key: uniqueFileName,
ContentType: $scope.file.type,
Body: $scope.file,
ServerSideEncryption: 'AES256'
};
bucket.putObject(params, function(err, data) {
if (err) {
console.log(err.message);
return false;
} else {
// Upload Successfully Finished
console.log('File Uploaded Successfully');
}
})
} else {
// No File Selected
console.log('Please select a file to upload');
}
}
file in my bucket - made public - crossdomain.xml
<cross-domain-policy>
<allow-access-from domain="*" secure="false"/>
</cross-domain-policy>
What is the setting I need to do to get rid of the first said error? Thanks.
To get rid of the error, I had to install cors..
npm install cors
in addition to that, I had a mistake in my region to be set to us-east-1 which was earlier us-west-2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.