如何使用ajax上传图像文件?

时间:2015-01-21 05:45:44

标签: php jquery

使用ajax上传图像MVC时出现

问题,我在类设置中调用了control_class.php内容函数upload_img_admin来自页面c_ajax_img.php

页面c_ajax_img.php

include_once('controls_class.php');
$ajax_up_img = new settings;
$ajax_up_img->upload_img_admin(@$_FILES['file_upload']);

在课堂设置中使用upload_img_admin

function upload_img_admin()
{
        $dir_name=dirname(__FILE__)."/upload/";
        $path=@$_FILES['file_upload']['tmp_name'];
        $name=@$_FILES['file_upload']['name'];
        $size=@$_FILES['file_upload']['size'];
        $type=@$_FILES['file_upload']['type'];
        $error=@$_FILES['file_upload']['error'];  
                   ...
                   ...

if( isset($_FILES['file_upload']) )
    {
        move_uploaded_file($path,$dir_name.$name);
                      ...
                      ...
        echo "ok";

     }
     else
     {
         echo "File not found";
      }

 }

函数ajax获取数据格式并发送到上传图像的函数

$(document).ready(function() {
$(".btn_upload_avatar").click(function(e) {
$('.msgerror').hide().fadeIn(1000).html(  '<div class="loading"></div>');
e.preventDefault();
$.ajax({
type:"POST",
url: "../controls/c_ajax_img.php",
cache: false,  
processData:false, 
contentType: false,
data:$("#form_up_img").serialize(),
success: function (data)
{
    if(data == 0){                  
     $('.msgerror').addClass('msgerror_in2').html(data);    
 }else{ 
    $('.msgerror').addClass('msgerror_in2').html(data); 
}
}   
});
});
});

1 个答案:

答案 0 :(得分:1)

这样的事情可能会帮助你交配.. :)

$(document).ready(function () {
      $('#UploadForm').on('submit',(function(e) {
          $('.msgerror').hide().fadeIn(1000).html('<div class="loading"></div>');
          e.preventDefault();
          var formData = new FormData(this);
          formData.append('file', input.files[0]);

          $.ajax({
              url: '../controls/c_ajax_img.php',
              data: formData,
              contentType: false,
              type: 'POST',
              processData: false,
              success: function (data) {
                  console.log("success");
                  console.log(data);
              },
              error: function (data) {
                  console.log("error");
                  console.log(data);
              }
          });
      });
  });

<强> FYI

FormData

ProcessData 设置为false,以防止jQuery自动将数据转换为查询字符串