weixin_33698823 2017-09-23 05:21 采纳率: 0%
浏览 41

S3 Ajax CORS错误

I have been trying to solve this for the past few hours.

I am using the Heroku S3 python app direct upload method outlined here.

Basically, I have a file input which I get the file from with

$('#files').on('change', function() {
    var files = document.getElementById("files").files;
    var file = files[0];
    if(!file){
       return alert("No file selected.");
    }
    getSignedRequest(file);
})

In getSignedRequest, I make a request to my sign_s3 route

function getSignedRequest(file){
          var xhr = new XMLHttpRequest();
          xhr.open("GET", "/sign_s3?file_name="+file.name+"&file_type="+file.type);
          xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
              if(xhr.status === 200){
                var response = JSON.parse(xhr.responseText);
                uploadFile(file, response.data, response.url);
              }
              else{
                alert("Could not get signed URL.");
              }
            }
          };
          xhr.send();
        }

The sign_s3 route is defined as follows

@main.route('/sign_s3/')
def sign_s3():
  S3_BUCKET = os.environ.get('S3_BUCKET')

  file_name = request.args.get('file_name')
  file_type = request.args.get('file_type')

  s3 = boto3.client('s3')

  presigned_post = s3.generate_presigned_post(
    Bucket = S3_BUCKET,
    Key = file_name,
    Fields = {"acl": "public-read", "Content-Type": file_type},
    Conditions = [
      {"acl": "public-read"},
      {"Content-Type": file_type}
    ],
    ExpiresIn = 3600
  )

  return json.dumps({
    'data': presigned_post,
    'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name)
  })

The uploadFile function is defined as follows

function uploadFile(file, s3Data, url){
          var xhr = new XMLHttpRequest();
          xhr.open("POST", s3Data.url);

          var postData = new FormData();
          for(key in s3Data.fields){
            postData.append(key, s3Data.fields[key]);
          }
          postData.append('file', file);
          console.log(file);

          xhr.onreadystatechange = function() {
            if(xhr.readyState === 4){
              if(xhr.status === 200 || xhr.status === 204){
                document.getElementById("preview").src = url;
                document.getElementById("avatar-url").value = url;
              }
              else{
                alert("Could not upload file.");
              }
           }
          };
          xhr.send(postData);
        }
      });

My bucket CORS config is as follows

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>http://localhost:5000</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
  </CORSRule>
</CORSConfiguration>

But I keep getting the following error upon fileUpload

Failed to load https://mhealth-beta-1.s3.amazonaws.com/: Redirect from 'https://mhealth-beta-1.s3.amazonaws.com/' to 'https://mhealth-beta-1.s3-us-west-2.amazonaws.com/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.
  • 写回答

1条回答 默认 最新

  • 谁还没个明天 2017-09-23 06:55
    关注

    The error is mentioning a redirect. I'm not familiar with how 302 redirects interact with CORS but try this:

    In your backend route, use the dns name including the region.

    so 'https://%s.s3.%s.amazonaws.com/%s' % (S3_BUCKET, region, file_name)

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!