I'm trying to send a file on another domain but progress event
isn't working. If I comment onprogress
function, the file is well uploaded, else an error occurs :
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.
Here is the code :
$("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;
}
I can't modify another-domain.com
because it's an API.
I tried to use AJAX
, File Upload
but I can't use progress
event too.
Any idea ?
EDIT
Here is another solution with 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();
}
});