我正在通过 ajax 向服务器端 PHP 发送(可能)多个用户输入文件。我使用 FormData()
对象发送它,当我在 PHP 中调用 $_FILES
时,它说 FormData
中的文件对象键是一个“未识别的索引。”我知道我破坏了解释,所以这里是上下文:
HTML:
<form id="subForm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple/>
<button type="submit">Post</button>
</form>
JQuery:
var files = $('input[type=file]').prop('files')[0]; //File list
var formData = new FormData();
//Cycle through files (if many)
for (var i = 0; i < files.length; i++) {
var file = files[i]; //File
//Type and size check
if (!file.type.match('image/*') && !file.type.match('video/*') && file.size > 8388608){
continue;
}
// Add the file to the request.
formData.append('files', file, file.name);
}
$.ajax({
type: 'POST',
url: 'submission.php', //Serverside handling script
enctype: 'multipart/form-data',
dataType: 'text', //Get back from PHP
processData: false, //Don't process the files
contentType: false,
cache: false,
data: formData,
success: function(php_script_response){
console.log(php_script_response);
}
});
PHP:
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
if(is_uploaded_file($_FILES['files']['tmp_name'][$key]) && $_FILES['files']['tmp_name'][$key]['error']==0) {
$path = 'uploads/' . $_FILES['files']['name'][$key];
$upload = true;
if(file_exists($path)){
//Re-Upload
$upload = false;
}
if(move_uploaded_file($_FILES['files']['name'][$key], $path)){
//Success
}else{
//Failure
}
}else{
//File not uploaded/ saved?
}
}
PHP 中的第 1 行返回:
Undefined index: files in C:\xampp\htdocs\submission.php
我的猜测是我的本地 apache 服务器或 JQuery 有问题?
提前致谢
最佳答案
永远不会到达 append
,因为您仅使用 .prop('files')[0]
从输入中获取单个值。因此,files.length
在循环中未定义。您应该获取整个文件数组:
var files = $('input[type=file]').prop('files'); //File list
关于php - 接收文件)通过服务器端 PHP 中的 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37284865/