我想在另一個域上發送文件,但progress event
不起作用。如果我評論onprogress
功能,該文件所上傳的,否則會出現錯誤:如何使用XMLHttpRequest發送跨域的文件?
OPTIONS http://another-domain.com No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mywebsite.com' is therefore not allowed access. XMLHttpRequest cannot load http://another-domain.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mywebsite.com' is therefore not allowed access.
下面是代碼:
$("form").on("submit", function(e) {
e.preventDefault();
var file = $("#file")[0].files[0];
var fd = new FormData();
fd.append("Filedata", file);
var xhr = getXDomainRequest();
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded/e.total) * 100;
console.log(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
}
};
xhr.open('POST', 'http://another-domain.com', true);
xhr.send(fd);
});
function getXDomainRequest() {
var xdr = null;
if (window.XDomainRequest)
xdr = new XDomainRequest();
else if (window.XMLHttpRequest)
xdr = new XMLHttpRequest();
else
alert("Cross Domain not supported");
return xdr;
}
我不能修改another-domain.com
因爲它是一個API。
我試圖使用AJAX
, File Upload
但我不能使用progress
事件。
有什麼想法?
編輯
這裏是File Upload
$('#fichier').fileupload({
dataType: "jsonp", // API error
beforeSend : function() {
$("#upload_progression_pj").show();
},
progress: function (e, data) {
var actuel = Math.round(data.loaded * 100/data.total);
log(actuel);
$("#upload_progression_pj span").html(actuel + "%");
},
done: function (e, data) {
$("#upload_progression_pj").hide();
$("#upload_progression_pj span").empty();
}
});
在您的調用中使用'jsonp'作爲'dataType',或者將頭部'Access-Control-Allow-Origin'設置爲適當的值。 – verisimilitude