2016-07-25 85 views
2

我正在研究一个允许用户将图像和数据提交到我们的服务器的Web应用程序(使用JQuery版本2.2.4)。当用户决定上传他们的提交内容时,我的代码应该使用JSZip库生成一个zip文件并使用POST将其上传到我们的服务器。某些搜索这里StackExchange后,我想出了这个代码:在Javascript中使用POST上传zip文件失败,无提示

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); 
}); 

但是,这并不被触发。在设置错误回调方面显然存在一些错误 - 我可以尝试什么?

回答

1

我设法让上传工作创造一个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答案的启发。

1

我想你没有看到任何POST,因为你的数据对象不只包含字符串值(如果我使用{data: "content"},我得到一个POST)。

https://stackoverflow.com/a/19015673https://stackoverflow.com/a/18254775,你需要添加一些参数(documentation):

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

随着您的修改,我得到一个HTTP错误400(错误的请求)。 – Btz

+0

您链接的答案对解决我的问题非常有帮助!我创建了一个新的答案,以便我可以放置代码。 – Btz