0
我一直試圖解決這個過去的幾個小時。S3 Ajax CORS錯誤
我正在使用Heroku S3 python應用程序直接上傳方法概述here。
基本上,我有一個文件輸入,我從
$('#files').on('change', function() {
var files = document.getElementById("files").files;
var file = files[0];
if(!file){
return alert("No file selected.");
}
getSignedRequest(file);
})
在getSignedRequest得到的文件,我主動要求我sign_s3
航線
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();
}
的sign_s3
路線定義如下
@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)
})
uploadFile函數是d efined如下
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);
}
});
我鬥CORS配置如下:
<?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>
但在文件上傳
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.
這是一個很好的追趕 - 重定向確實是意想不到的,這至少應該消除一個潛在的問題,但要注意,'S3 - $ {}區域是.amazonaws.com'無效所有地區。只有較早的地區使用該格式。較新的區域在's3'後面使用點而不是短劃線,而us-east-1使用's3-external-1'。目前唯一有效的一貫模式是'bucket.s3.dualstack。$ {region} .amazonaws.com'。我總是從「localhost」不是CORS測試的有效來源的假設開始工作,因爲它不是一個真正的域。 –
我很確定點符號在任何地方都受支持,儘管這沒有明確記錄。無論如何,這不是OP的問題。 – prestomation
是的,他們似乎已經在舊區域推出了新的SSL證書來支持點符號,但它歷史上並沒有這種方式,並且(尚未)在[區域和端點](http:// docs.aws.amazon.com/general/latest/gr/rande.html#s3_region)。同意......但這不是問題,在這裏。 –