3

我正在开发一个允许用户向我们的服务器提交图像和数据的 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 object created消息,文件对象本身看起来不错,但是我什么也没得到。无声的失败。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);
});

但这不会被触发。显然我在设置错误回调时犯了一些错误 - 我可以尝试什么?

4

2 回答 2

3

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

于 2016-07-26T11:51:52.420 回答
1

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

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

$.post({
  url: "/test",
  data: fileObj,
  contentType: false,
  processData: false
})
于 2016-07-25T18:43:44.790 回答