php使用ajax上传多个文件

时间:2014-12-16 08:16:08

标签: javascript php jquery ajax forms

我已经设法使用我当前的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 '<pre>', print_r($_POST, 1), '</pre>';
}

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

html表单

<form id="folder_upload" action="" method="post" enctype="multipart/form-data">
              <input type="file" class="hide" name="files[]" id="folder_open_id" multiple directory webkitdirectory mozdirectory/>
              <input type="submit" class="hide" value="upload" id="folder_open_upload" />
        </form>

在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); }
    });

1 个答案:

答案 0 :(得分:5)

根据一些初步研究,利用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