php使用ajax上传多个文件

我已经设法使用我当前的php和html表单上传了多个文件,并希望通过一些ajax并自动提交表单。 我已经隐藏了’文件’输入和提交按钮,因此表格由js处理(提及这可能会影响表单提交,表单提交,我通过HTTP标头检查)。 我的js的ajax部分是我通常用于ajax和标准表单的,但是当我提交表单时我的$ _FILES是空的,所以我想我在这里没有正确使用ajax? 我需要在我的ajax中更改以处理文件上传?

$("#add_button").click(function(e) { e.preventDefault(); $("#folder_open_id").trigger("click"); $("#folder_open_id").change(function() { $("#folder_upload").submit(); }); }); $("#folder_upload").submit(function(event) { var formdata = $(this).serialize(); event.preventDefault(); $.ajax ({ url: "index.php", type: "POST", data: formdata, success: function(response) { $("#response_div").html(response); }, error: function(response) { alert(response); } }); }); 

PHP

  if($_SERVER['REQUEST_METHOD'] == 'POST') { if(!empty($_FILES['files']['name'][0])) { $files = $_FILES['files']; define('CPATH', $_SERVER['DOCUMENT_ROOT'] . "/uploads/"); $uploaded = array(); foreach($files['name'] as $position => $file_name) { $file_temp = $files['tmp_name'][$position]; $file_new = "./uploads/" . $files['name'][$position]; if(move_uploaded_file($file_temp, $file_new)) echo "success"; else echo "fail, temp: " . $file_temp . " new: " . $file_new; } } else echo '
', print_r($_POST, 1), '

'; }

所以empty($_FILES['files']['name'][0]返回true,而print_r($ _ POST)似乎是空的。

HTML表单

 

在Mephoros回答之后,这是我的js,我的$ _FILES数组似乎仍然是空的:

 $.ajax ({ url: "index.php", type: "POST", data: new FormData($(this)), processData: false, contentType: 'multipart/form-data; charset=UTF-8', success: function(response) { $("#response_div").html(response); }, error: function(response) { alert(response); } }); 

基于一些初步研究,利用FormData并将处理和contentType设置为false。

 $.ajax({ // ... data: new FormData($(this)), processData: false, contentType: false, // ... }); 

资料来源:

请参阅: http : //api.jquery.com/jquery.ajax/

请参阅: https : //developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects