2017-05-20 115 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

相关问题