我已经编写了使用直接从浏览器使用角js将图像上传到amazon s3的代码。为此,我使用了库aws-sdk. js。我有一个函数“上传”,其中我分配凭据和参数以及文件。上传时,我得到以下错误
*No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access*.
我的CORS配置
<?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>
我的控制器功能
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');
}
}
我的存储桶中的文件-公共-交叉域. xml
<cross-domain-policy>
<allow-access-from domain="*" secure="false"/>
</cross-domain-policy>
为了消除第一个错误,我需要做什么设置?谢谢。
为了摆脱错误,我不得不安装cors…
npm安装cors
除此之外,我在我的地区有一个错误,设置为us-East-1,这是更早的us-West-2