亚马逊s3上传使用javascript sdk无法正常工作

时间:2014-04-22 09:13:23

标签: javascript amazon-s3

我正在使用javascript amazon sdk将内容上传到亚马逊。我试试这个例子。这是我的代码。

  <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: 'keyid', secretAccessKey: 'secretkey'});

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


    <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: 'bucket_name'}});

    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 ? 'ERROR!' : 'UPLOADED.';
       });
   } else {
      results.innerHTML = 'Nothing to upload.';
   }
   }, false);
  </script>

但是我收到了这个错误

但我收到了这个错误

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

经过一些研究后,我知道这是一个跨域问题。但我不知道如何解决这个问题。此代码直接取自亚马逊文档

1 个答案:

答案 0 :(得分:0)

这实际上是一个CORS问题。你有没有检查过S3 documentation的这一部分。

link也必须有用:)