PHP的上传与阿贾克斯多个文件 [英] php Uploading multiple files with ajax

查看:164
本文介绍了PHP的上传与阿贾克斯多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功使用我目前的PHP和HTML表单上传多个文件,并希望就看中了位与一些Ajax和自动提交表单。我已经隐藏了文件输入并提交按钮,这样的形式被JS handeled(提到这一点,以防可能会影响表单提交,形式不提交,我已经通过HTTP头检查)。我JS的AJAX部分我通常对AJAX和标准格式,但用什么,当我提交表单我的$ _FILES是空的,所以我想我没有使用AJAX正确吗?我需要做什么在我的AJAX改变来处理文件上传?

  $(#add_button)。点击(函数(五)
   {
       即preventDefault();
       $(#folder_open_id)触发(点击)。
       $(#folder_open_id)。改变(函数()
       {
          $(#folder_upload)提交()。
       });
   });


   $(#folder_upload)。递交(函数(事件)
   {
        VAR FORMDATA = $(本).serialize();
        。事件preventDefault();

        $就
        ({
           网址:的index.php
           键入:POST,
           数据:FORMDATA,
           成功:函数(响应){$(#response_div)HTML(响应); },
           错误:功能(响应){警报(响应); }
        });
    });
 

PHP

 如果($ _ SERVER ['REQUEST_METHOD'] =='POST')
{
    如果(!空($ _ FILES ['文件'] ['名称'] [0]))
    {

        $文件= $ _FILES ['文件'];
        定义(CPATH',$ _ SERVER ['DOCUMENT_ROOT']/上传/);
        $上传=阵列();

        的foreach($文件['名称']为$位置=> $ FILE_NAME)
        {
            $ file_temp = $文件['tmp_name的值'] [$位置]
            $ file_new =./uploads/。 $文件[名称] [$位置]

                如果(move_uploaded_file($ file_temp,$ file_new))
                    回声成功;
                其他
                    回声失败,温度:。 $ file_temp。  新:  。 $ file_new;
        }
    }
    其他
        回声'< pre>,的print_r($ _ POST,1),'< / pre>';
}
 

空($ _ FILES ['文件'] ['名称'] [0] 将返回true,并且的print_r($ _ POST)是空的,似乎

HTML表单

 <形式ID =folder_upload行动=的方法=邮报是enctype =的multipart / form-data的>
              <输入类型=文件级=隐藏名称=文件[]ID =folder_open_id多个目录webkitdirectory mozdirectory />
              <输入类型=提交级=隐藏值=上传ID =folder_open_upload/>
        < /形式GT;
 

下面是Mephoros的回答后,我的JS,我的$ _FILES数组似乎仍然是空的:

  $。阿贾克斯
    ({
       网址:的index.php
       键入:POST,
       数据:新FORMDATA($(本)),
       过程数据:假的,
       的contentType:的multipart / form-data的;字符集= UTF-8,
       成功:函数(响应){$(#response_div)HTML(响应); },
       错误:功能(响应){警报(响应); }
    });
 

解决方案

根据一些preliminary研究,利用FORMDATA并设置加工的contentType为false。

  $。阿贾克斯({
  // ...
  数据:新FORMDATA($(本)),
  过程数据:假的,
  的contentType:假的,
  // ...
});
 

来源:

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

请参阅: https://developer.mozilla.org/en-美国/文档/网页/指南/ Using_FormData_Objects

I've managed to upload multiple files using my current php and html form and wanted to fancy it up a bit with some ajax and automatically submitting the form. I've hidden the 'file' input and submit button so the form is handeled by the js (mentioning this incase it may affect form submission, form does submission and I've checked via HTTP headers). The ajax section of my js is what I normally use for ajax and standard forms, however when i submit the form my $_FILES is empty so I guess I'm not using the ajax correctly here? What do I need to change in my ajax to handle file uploads?

    $("#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>';
}

so empty($_FILES['files']['name'][0]is returning true and the print_r($_POST) is empty it seems.

html form

<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>

Here is my js after Mephoros answer, my $_FILES array still seems to be empty:

$.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); }
    });

解决方案

Based on some preliminary research, utilize FormData and set processing and contentType to false.

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

Sources:

See: http://api.jquery.com/jquery.ajax/

See: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

这篇关于PHP的上传与阿贾克斯多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆