在本地服务器上,我的上传文件和进度条按预期工作。当我上传到我们的测试服务器(使用CORS进行上传)时,XHR进程回调会导致一些CORS问题。
无法加载XMLHttpRequest。对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源''因此不允许访问。
我们已经在服务器和ajax请求上启用了CORS,这是首先让上传工作跨越原点所必需的,但是关于XHR字段的一些事情导致它抛出该错误。
$.ajax({
url: chatOptions.siteRoot + 'obfuscatingthispartofurl/controller?param=' + user.RoomName,
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
type: 'POST',
xhrFields: {
withCredentials: chatOptions.useCors
},
crossDomain: chatOptions.useCors,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.withCredentials = xhr.useCredentials = chatOptions.useCors;
xhr.crossDomain = chatOptions.useCors;
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log("upload is " + Math.round(percentComplete*100) + "% complete.");
var elem = document.getElementById("upload-progress-bar");
elem.style.width = Math.round(percentComplete * 100) + '%';
document.getElementById("upload-progress-bar").innerHTML = Math.round(percentComplete * 100) + '%';
}
}, false);
return xhr;
},
success: function (result) {
document.getElementById("file-upload-input").value = "";
console.log(result);
if (result == "success")
chat.server.sendDownload(file.name, file.size);
$('#file-upload-input').hide();
$('#file-upload-input-label').hide();
$('#upload-progress-div').hide();
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;