繁体   English   中英

php用ajax上传多个文件

[英]php Uploading multiple files with 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 '<pre>', print_r($_POST, 1), '</pre>';
}

因此为empty($_FILES['files']['name'][0]似乎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); }
    });

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM