Sending generated (JSZip) zip file in XmlHttprequest (javascript)

家住魔仙堡 提交于 2019-12-25 02:44:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!