2013-02-11 113 views
0

我有一個文件輸入類型的HTML表單。我需要將表單異步提交給服務器。服務器偵聽傳入文件上傳(多部分文件上傳)請求。是否有可能實現這個使用jQuery。異步JQUERY文件上傳

+1

可能重複的[我怎樣才能上傳文件與jQuery異步?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – gdoron 2013-08-31 19:33:35

回答

2

您可以輕鬆地使用jQuery的$.ajax()方法來發送文件,如果FormDataFile API支持(包括HTML5功能)。

您也可以發送文件without FormData,但無論採用哪種方式,都必須存在File API來處理文件,以便可以使用XMLHttpRequest(Ajax)發送文件。

$.ajax({ 
    url: 'file/destination.html', 
    type: 'POST', 
    data: new FormData($('#formWithFiles')[0]), // The form with the file inputs. 
    processData: false // Using FormData, don't process data. 
}).done(function(){ 
    console.log("Success: Files sent!"); 
}).fail(function(){ 
    console.log("An error occurred, the files couldn't be sent!"); 
}); 

有關快速,純粹的JavaScript示例,請參閱「Sending files using a FormData object」。

如果你想添加一個後備舊版本瀏覽器,或者如果你只想要一個跨瀏覽器實現使用Bifröst。它增加了一個額外的jQuery Ajax transport允許發送文件與飛機舊$.ajax()

只需添加jquery.bifrost.js和發出請求:

$.ajax({ 
    url: 'file/destination.html', 
    type: 'POST', 
    // Set the transport to use (iframe means to use Bifröst) 
    // and the expected data type (json in this case). 
    dataType: 'iframe json',         
    fileInputs: $('input[type="file"]'), // The file inputs containing the files to send. 
    data: { msg: 'Some extra data you might need.'} 
}).done(function(){ 
    console.log("Success: Files sent!"); 
}).fail(function(){ 
    console.log("An error occurred, the files couldn't be sent!"); 
}); 

祝你好運!