AWS S3 File upload using Javascript

前提是你 提交于 2019-12-24 19:42:06

问题


I'm trying to upload an image to aws s3 using javascript. But when i attempt to upload it, I'm getting the following error.

Failed to load https://demoapp.s3-us-west-2.amazonaws.com/IMG_2484.JPG: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

Code :

<input id="file-chooser" type="file"/>
<button id="upload-button">Upload</button>
<p id="results"></p>

Javascript :

<script>
var credentials = {
    accessKeyId: 'XXXXX',
    secretAccessKey: 'XXXXXXX'
};
AWS.config.update(credentials);
AWS.config.region = 'us-west-2';

// create bucket instance
var bucket = new AWS.S3({params: {Bucket: 'demoapp'}});

var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
button.addEventListener('click', function () {
    var file = fileChooser.files[0];
    if (file) {
        results.innerHTML = '';

        var params = {Key: file.name, ContentType: file.type, Body: file, 'Access-Control-Allow-Credentials': '*'};
        bucket.upload(params, function (err, data) {
            results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
        });
    } else {
        results.innerHTML = 'Nothing to upload.';
    }
}, false);

I configured the CORS as follows.

CORS configuration


回答1:


The error ... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource... suggests a CORS misconfiguration, but in this specific case, the pre-flight check fails for a different reason: the request was not being sent to the correct S3 regional endpoint for the bucket.

S3 is a global service, but each individual bucket is constrained to exist in one specific region of S3. All regions are aware of the correct location for all buckets, but are not able to access them. Only the region that actually contains a particular bucket has access to that bucket, so requests arriving at other regions due to misconfiguration can't be processed.

When a request is sent to the wrong region, S3 throws an error... sort of. It actually returns a 30X HTTP redirect response, but the redirect does not include the customary Location header, so it isn't a redirect that the browser can follow.

Perhaps more important for the issue at hand, that response also does not contain the CORS response headers necessary for a successful pre-flight check... so a request sent to a bucket properly configured for CORS support will still fail the pre-flight check if the request is being sent to the wrong S3 regional endpoint.



来源:https://stackoverflow.com/questions/48477579/aws-s3-file-upload-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!