使用ajax发送输入类型文件

时间:2016-03-28 19:44:11

标签: php jquery ajax html5

好吧,我被困了几个小时, 我只是想使用ajax上传用户profil pic,但我不能去 将文件发送到执行上传的ajax2.PHP! 这是我的代码

    <script>
    $(document).ready(function(){

        //trigger change picture when click on the picture
          $("#changelogox").on('click', function() {
            $('#logopicsxda').click();
        });


    });
    </script>
    <script>

    $(function(){ 
            $('#savelogox').click(function(){
                  var formData = new FormData($('#ff')[0])


                $.ajax({

                    type:"POST",
                    url:"ajax2.php",
                    data:'act=save'+FormData,
                    success: function(data){

    alert(data);
                    }
                });
     });
     });



    </script>
    <form id="ff" action="" method="post" enctype="multipart/form-data">
    <img  id="logoc" src="images/logo2.jpg" class="logo">
    <span id="contacxkr"><span class="xaox" id="changelogox">Change</span>
    <br>
    <br>

    <span class="xaoxx" id="savelogox">save</span></span>

        <input type="hidden" name="MAX_FILE_SIZE" value="2048000" />

    <input  style="display: none;" name="myimage" type='file' multiple accept='image/*' id='logopicsxda' /></form>

这是我的ajax2.php代码,用于向服务器和数据库上传

<?php

include('core/init.php');
    extract($_POST);
$username=$user_data['username'];


            $posted_data = print_r($_POST,true);
file_put_contents('debug.txt',$posted_data);


    if($act == 'save'): //if the user click on "like"



             include 'config2.php';

        $file = $_FILES['myimage'];

$file_name = $file['name'];


$error = ''; // Empty

// Get File Extension (if any)

$ext = strtolower(substr(strrchr($file_name, "."), 1));

// Check for a correct extension. The image file hasn't an extension? Add one

   if($validation_type == 1)
   {
   $file_info = getimagesize($_FILES['myimage']['tmp_name']);

      if(empty($file_info)) // No Image?
      {
      $error .= "ERROR! The uploaded file doesn't seem to be an image.";
      }
      else // An Image?
      {
      $file_mime = $file_info['mime'];


         if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
         {
         $extension = $ext;
         }
         else
         {
         $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
         }

         if(!$extension)
         {
         $extension = '';  
         $file_name = str_replace('.', '', $file_name); 
         }
      }
   }
   else if($validation_type == 2)
   {
      if(!in_array($ext, $image_extensions_allowed))
      {
      $exts = implode(', ',$image_extensions_allowed);
      $error .= "ERROR! You must upload a file with one of the following extensions: ".$exts;
      }

      $extension = $ext;
   }

   if($error == "") // No errors were found?
   {
   $new_file_name = strtolower($file_name);
   $new_file_name = str_replace(' ', '-', $new_file_name);
   $new_file_name = substr($new_file_name, 0, -strlen($ext));
   $new_file_name .= $extension;
  $new_file_name = uniqid() . $username.$new_file_name;

   // File Name

   $move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);


   if($move_file)
       {
$query= $pdo->prepare("UPDATE users SET profilepic=?  WHERE username= ?");

        $query->bindValue(1,$new_file_name);
            $query->bindValue(2,$username);
        $query->execute();




       }
   }
   else
   {
   @unlink($file['tmp_name']);
   }
    endif;

?> 

问题是我无法弄清楚当我调试它时如何将文件发送到ajax2.php我得到了这个

Array
(
    [act] => savefunction FormData() { [native code] }
)

1 个答案:

答案 0 :(得分:0)

如果要使用FormData向ajax请求添加更多字段,则必须将数据附加到对象

var formData = new FormData($('#ff')[0]);
formData.append('act','save');

对于使用FormData的$ .ajax,您必须将contentType和processData设置为false。

 $.ajax({

    type:"POST",
    url:"ajax2.php",
    data: formData,
    contentType: false,
    processData: false,
    success: function(data){

        alert(data);
    }
});