2017-05-20 116 views
0

我想用JS發送數組文件。我的代碼:使用Ajax發送FileList到PHP腳本

var formData = new FormData(); 
formData.append("files", files); 

$.ajax({ 
    url: './upload.php', 
    method: 'post', 
    data: formData, 
    processData: false, 
    contentType: false, 
success: function(response) { 
    alert('Files uploaded successfully. '); 
    console.log(response); 
}, 
error: function(jqXHR, textStatus, errorThrown) { 
    console.log(textStatus, errorThrown); 
} 

}); 

在此圖像中可以看到從PHP https://beta.ctrlv.cz/mUwx響應(紅色),你也可以看到這些文件陣列數據。我的PHP代碼:

<?php 
    echo $_POST['files'][0]["name"]; 
?> 

我想使用PHP腳本上傳,但AJAX沒有發送文件的陣列,這是重要的上傳。

+0

確定它的'$ _POST'而不是'$ _FILES'? – Xorifelse

+0

另外,[如何閱讀](http://stackoverflow.com/documentation/php/2781/security/29134/uploading-files)瞭解如何使用PHP安全地上傳文件。 – Xorifelse

+0

當我寫print_r($ _ FILES)時,輸出爲空:「Array ( )」,所以我不知道..我會讀它,但首先,我需要有工作上傳, 。 – Alex

回答

0

採取下面是我找到了答案:

var data = new FormData(); 
jQuery.each(jQuery('#file')[0].files, function(i, file) { 
    data.append('file-'+i, file); 
}); 

所以,現在你有一個FormData對象,隨時可以用的XMLHttpRequest一起發送。

jQuery.ajax({ 
    url: 'php/upload.php', 
    data: data, 
    cache: false, 
    contentType: false, 
    processData: false, 
    type: 'POST', 
    success: function(data){ 
     alert(data); 
    } 
}); 

這裏來源:https://stackoverflow.com/a/5976031/7282094

希望可以幫助。

+0

Uncaught TypeError:無法在uploadFiles(index.php?dir = u_tchosniper:342) 在HTMLButtonElement.onclick(index.php?dir = u_tchosniper:238)處讀取未定義的 屬性「文件」 – Alex

+0

今天我嘗試修復代碼和它的工作,非常感謝你。 – Alex

0

更改contentType: false,contentType: "multipart/form-data",可能。

http://api.jquery.com/jquery.ajax/

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') Type: Boolean or String When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

+0

結果是print_r($ _ POST),$ _FILES是「Array()」。 – Alex

相關問題