通过服务器端PHP中的AJAX接收文件



我正在通过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行返回:

未定义的索引:C:\examplep\htdocs\submission.php中的文件

我的猜测是,要么是我的本地apache服务器出了问题,要么是JQuery出了问题?

提前感谢

append永远不会到达,因为您使用.prop('files')[0]只从输入中获取一个值。因此,files.length在循环中是未定义的。您应该获取整个文件阵列:

var files = $('input[type=file]').prop('files'); //File list

最新更新