直接从浏览器将图像上传到amazon s3 - 使用angular js

时间:2014-09-20 13:23:46

标签: javascript angularjs amazon-web-services amazon-s3

我已经编写了使用浏览器直接使用angular 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');
    }
}

我的存储桶中的文件 - 公开 - crossdomain.xml

<cross-domain-policy>
<allow-access-from domain="*" secure="false"/>
</cross-domain-policy>

我需要做什么设置才能摆脱第一个错误?感谢。

1 个答案:

答案 0 :(得分:0)

为了摆脱这个错误,我不得不安装cors ..

npm install cors

除此之外,我在我的地区犯了一个错误,设置为us-east-1,这是早期的us-west-2