问题
i'am design a web application in which i create a set of file from user input, zip them using the JSZip library and then try to post the files to a server using Xhr. The code is the following :
var content = zip.generate({type : "blob"});
var server_path = document.getElementById('build_server').value;
server_path = server_path + '/upload_project';
console.log(server_path);
global_oreq = new XMLHttpRequest();
var file_name = design_name + '.zip';
var formData = new FormData();
var json_build_answer = '';
global_oreq.open("POST", server_path, true);
global_oreq.onload = function(e) {
// json_build_answer = JSON.parse(oReq.responseText);
console.log('test');
console.log(global_oreq.responseText);
};
formData.append('file', content, file_name);
global_oreq.send(formData);
My problem with this piece of code is that the onload function is never called. I assumed that this is because my function quits before the ned of the request so i turned the Xhr request synchronous setting false in the arguments. This resulted in a NS_ERROR. I read that Xhr cannot perform request on distant domain. Is that true ? What would you do to address this problem. ? From what is see on the server side (the one i'am posting to) is that the file is received and the json response returned. It just seems that the client side never receive the response.
Thanks for your help !
回答1:
use this
var content = zip.generate({type : "blob"});
var server_path = document.getElementById('build_server').value;
server_path = server_path + '/upload_project';
console.log(server_path);
var global_oreq = new XMLHttpRequest();
var file_name = design_name + '.zip';
var formData = new FormData();
var json_build_answer = '';
global_oreq.open("POST", server_path, true);
global_oreq.onload = function(e) {
// json_build_answer = JSON.parse(oReq.responseText);
console.log('test');
console.log(global_oreq.responseText);
};
formData.append('file', content, file_name);
global_oreq.send(formData);
来源:https://stackoverflow.com/questions/21748168/sending-generated-jszip-zip-file-in-xmlhttprequest-javascript