在Javascript中使用POST上传zip文件会无声地失败

我正在开发一个Web应用程序(使用JQuery 2.2.4版),允许用户将图像和数据提交给我们的服务器。 当用户决定上传他们的提交时,我的代码应使用JSZip库生成一个zip文件,并使用POST将其上传到我们的服务器。 在StackExchange上搜索了一下之后,我想出了这段代码:

var zip = new JSZip(); // Create the object representing the zip file // ...Add the data and images console.log('Generating compressed archive...'); zip.generateAsync({ compression: 'DEFLATE', type: 'blob' }).then(function(zc) {// Function called when the generation is complete console.log('Compression complete!'); // Create file object to upload var fileObj = new File([zc], fileName); console.log('File object created:', fileObj); $.post('http://myurl/submit', { data: fileObj, }).done(function() { console.log('Ajax post successful.'); }) .fail(function(jqXHR, textStatus, errorThrown) { console.log('Ajax post failed. Status:', textStatus); console.log(errorThrown); }); }); 

我的代码打印了File对象创建的消息,文件对象本身看起来没问题,但后来我什么都没得到。 沉默的失败。 POST调用甚至不出现在Firebug的Net面板中。

经过更多搜索,我还尝试事先添加此代码:

 $(document).ajaxError(function(event, jqxhr, settings, thrownError) { console.log('Ajax post failed. Event:', event); console.log('Ajax settings:', settings); console.log(thrownError); }); 

但这不会被触发。 我在设置错误回调时显然有些错误 – 我可以尝试一下吗?

我认为您没有看到任何POST因为您的数据对象不包含字符串值(如果我使用{data: "content"}我会收到POST )。

在https://stackoverflow.com/a/19015673和https://stackoverflow.com/a/18254775之后 ,您需要添加一些参数( 文档 ):

 $.post({ url: "/test", data: fileObj, contentType: false, processData: false }) 

我设法让上传工作创建一个FormData对象并将我的文件粘贴到它。 这是代码:

 var zip = new JSZip(); // Create the object representing the zip file // ...Add the data and images console.log('Generating compressed archive...'); zip.generateAsync({ compression: 'DEFLATE', type: 'blob' }).then(function(zc) {// Function called when the generation is complete console.log('Compression complete!'); // Create file object to upload var fileObj = new File([zc], fileName); console.log('File object created:', fileObj); var fd = new FormData(); fd.append('fileName', fileName); fd.append('file', fileObj); fd.append('mimeType', 'application/zip'); // POST Ajax call $.ajax({ type: 'POST', url: 'http://myurl/submit', data: fd, contentType: false, processData: false, }).done(function() { console.log('Ajax post successful.'); }).fail(function(jqXHR, textStatus, errorThrown) { console.log('Ajax post failed. Status:', textStatus); console.log(jqXHR); console.log(errorThrown); }); }); 

这是受David Duponchel链接的其他StackExchange答案的启发。