2016-07-25 55 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