ghost...
ghost...

Reputation: 1001

Upload doc to amazon s3 bucket with javascript: cors issue

I am trying to upload the doc/images to S3 bucket using javascript. I am facing CORS issue while doing the operation.

<script src="https://sdk.amazonaws.com/js/aws-sdk-2.0.0-rc13.min.js">    </script>
<script type="text/javascript">
  // See the Configuring section to configure credentials in the SDK
  // AWS.config.credentials = ...;
  AWS.config.update({ accessKeyId: 'mykeyid', secretAccessKey: 'mysecretkey' });

  // Configure your region
  AWS.config.region = 'us-west-2';

<input type="file" id="file-chooser" /> 
<button id="upload-button">Upload to S3</button>
<div id="results"></div>

<script type="text/javascript">
    var bucket = new AWS.S3({ params: { Bucket: 'ard1'} });

    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 cal_key = file.name;
            var params = { Key: cal_key, ContentType: file.type, Body: file };
            bucket.putObject(params, function (err, data) {

                results.innerHTML = err ? (err+data) : 'UPLOADED.';
            });
        } else {
            results.innerHTML = 'Nothing to upload.';
        }
    }, false);

My Cors configuration for the bucket on amazon is

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <ExposeHeader>ETag</ExposeHeader>
    <ExposeHeader>x-amz-meta-custom-header</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

It gives the following error:

XMLHttpRequest cannot load https://ard1.s3-us-west-2.amazonaws.com/Hydrangeas.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:59213' is therefore not allowed access.

Upvotes: 1

Views: 1112

Answers (1)

Travis White
Travis White

Reputation: 1977

Try adding this..

<AllowedOrigin>http://*</AllowedOrigin>
<AllowedOrigin>https://*</AllowedOrigin>

Also, seems like the objects in the bucket do not get updated to latest cors file... attempting to find a way to update all existing object's CORS information.

Upvotes: 3

Related Questions