search
HomeBackend DevelopmentPHP TutorialPHP结合jQuery插件ajaxFileUpload实现异步上传文件实例_PHP

平时用的比较多的JQuery图片上传插件是Uploadify这个插件,效果很不错,但是由于手机不支持flash,所以不得不再找一个文件上传插件来用了。后来发现ajaxFileUpload这个插件挺不错,所以就用这个插件来做异步上传文件的效果。网上也有很多对ajaxFileUpload插件的使用的文章,不过我发现没有PHP版,所以这次服务器那边的处理就使用PHP语言来处理。

一、详解ajaxFileUpload插件的语法参数

  原理:ajaxfileupload是通过监听iframe的onload方法来实现, 当从服务端处理完成后,就触发iframe的onload事件调用其绑定的方法,在绑定的方法中获取iframe中服务器返回的数据体(支持的普通文本,json,xml,script, html)

  语法:$.ajaxFileUpload([options])

二、接下来我们看看如何去使用

1、先引入ajaxFileUpload这个插件。

<script src="jquery-1.11.1.js" type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>

  这里我用的是jq1.11.1版本,网上有说jq版本与ajaxfileupload的版本要对应才不会有异常报错,反正我现在这个没错误。

2、贴上HTML的代码。

  <div data-role="fieldcontain" class="upload-box">
    <label for="id_photos"><span class="red">* </span>您的有效证件照:</label>
     <input type="file" id="id_photos" name="id_photos" value="上传" style="filter:alpha(opacity=10);-moz-opacity:10;opacity:10;" />   
    <p style="margin-top:0.5em;color:#999;font-size:11pt;">说明:请上传手持证件的半身照,请确保照片内证件信息清晰可读。</p>
  </div>
  <div class="id_photos" >
   
  </div> 

  此处主要的是这一句代码,其他的不用管,因为这里我是在手机端,用的是jqueryMobile插件。

3、到js代码进行处理。

$(document).bind('pageinit', function(){
 //照片异步上传
 $('#id_photos').change(function(){ //此处用了change事件,当选择好图片打开,关闭窗口时触发此事件
  $.ajaxFileUpload({
  url:'/uploader/', //处理图片的脚本路径
  type: 'post',  //提交的方式
  secureuri :false, //是否启用安全提交
  fileElementId :'id_photos',  //file控件ID
  dataType : 'json', //服务器返回的数据类型  
  success : function (data, status){ //提交成功后自动执行的处理函数
   if(1 != data.total) return;   //因为此处指允许上传单张图片,所以数量如果不是1,那就是有错误了
   var url = data.files[0].path;  
   $('.id_photos').empty();
   //此处效果是:当成功上传后会返回一个json数据,里面有url,取出url赋给img标签,然后追加到.id_photos类里显示出图片
   $('.id_photos').append('<img  src="/static/imghwm/default1.png"  data-src="'+url+'"  class="lazy"+url+'" value="'+url+'"   style="max-width:90%"  alt="PHP结合jQuery插件ajaxFileUpload实现异步上传文件实例_PHP" >');
   //$('.upload-box').remove();
  },
  error: function(data, status, e){ //提交失败自动执行的处理函数
   alert(e);
  }
 })
});

  这里我对每一行的代码都基本写上了注释方便大家理解。流程就是上传图片给uploader.php去处理,处理成功返回json数据,然后在json中取出url值,将其赋给img标签里,然后将img标签追加带页面显示出来。

  这里我附上json返回的数据:

{
 "total": 1,
 "success": 1,
 "files": [
  {
   "srcName": "3.jpg",
   "error": 0,
   "size": 10715,
   "type": "image/jpeg",
   "success": true,
   "path": "http://m.kellyblog.com/upload/20150528/857f4a35664b4a665e713322306d73b2.0x124x126.jpg",
   "width": 124,
   "height": 126
  }
 ]
}

  上传前HTML页面是这样的:

  异步上传成功后HTML页面效果是这样子的:

  

  4、看看PHP是如何处理的

class UploaderController extends XXXX_Controller {
 public function index() {
  $files = array();
  $success = 0; //用户统计有多少张图片上传成功了
  
  foreach ($_FILES as $item) {
   $index = count($files);

   $files[$index]['srcName'] = $item['name']; //上传图片的原名字
   $files[$index]['error'] = $item['error']; //和该文件上传相关的错误代码
   $files[$index]['size'] = $item['size'];  //已上传文件的大小,单位为字节
   $files[$index]['type'] = $item['type'];  //文件的 MIME 类型,需要浏览器提供该信息的支持,例如"image/gif"
   $files[$index]['success'] = false;   //这个用于标志该图片是否上传成功
   $files[$index]['path'] = '';    //存图片路径

   // 接收过程有没有错误
   if($item['error'] != 0) continue;
   //判断图片能不能上传
   if(!is_uploaded_file($item['tmp_name'])) {
    $files[$index]['error'] = 8000;
    continue;
   }
   //扩展名
   $extension = '';
   if(strcmp($item['type'], 'image/jpeg') == 0) {
    $extension = '.jpg';
   }
   else if(strcmp($item['type'], 'image/png') == 0) {
    $extension = '.png';
   }
   else if(strcmp($item['type'], 'image/gif') == 0) {
    $extension = '.gif';
   }
   else {
    //如果type不是以上三者,我们就从图片原名称里面去截取判断去取得(处于严谨性) 
    $substr = strrchr($item['name'], '.');
    if(FALSE == $substr) {
     $files[$index]['error'] = 8002;
     continue;
    }

    //取得元名字的扩展名后,再通过扩展名去给type赋上对应的值
    if(strcasecmp($substr, '.jpg') == 0 || strcasecmp($substr, '.jpeg') == 0 || strcasecmp($substr, '.jfif') == 0 || strcasecmp($substr, '.jpe') == 0 ) {
     $files[$index]['type'] = 'image/jpeg';
    }
    else if(strcasecmp($substr, '.png') == 0) {
     $files[$index]['type'] = 'image/png';
    }
    else if(strcasecmp($substr, '.gif') == 0) {
     $files[$index]['type'] = 'image/gif';
    }
    else {
     $files[$index]['error'] = 8003;
     continue;
    }
    $extension = $substr;
   }

   //对临时文件名加密,用于后面生成复杂的新文件名
   $md5 = md5_file($item['tmp_name']);
   //取得图片的大小
   $imageInfo = getimagesize($item['tmp_name']);
   $rawImageWidth = $imageInfo[0];
   $rawImageHeight = $imageInfo[1];

   //设置图片上传路径,放在upload文件夹,以年月日生成文件夹分类存储,
   //rtrim(base_url(), '/')其实就是网站的根目录,大家自己处理
   $path = rtrim(base_url(), '/') . '/upload/' . date('Ymd') . '/';
   //确保目录可写
   ensure_writable_dir($path);
   //文件名
   $name = "$md5.0x{$rawImageWidth}x{$rawImageHeight}{$extension}";
   //加入图片文件没变化到,也就是存在,就不必重复上传了,不存在则上传
   $ret = file_exists($path . $name) &#63; true : move_uploaded_file($item['tmp_name'], $serverPath . $name);
   if($ret === false) {
    $files[$index]['error'] = 8004;
    continue;
   }
   else {
    $files[$index]['path'] = $path . $name;  //存图片路径
    $files[$index]['success'] = true;   //图片上传成功标志
    $files[$index]['width'] = $rawImageWidth; //图片宽度
    $files[$index]['height'] = $rawImageHeight; //图片高度
    $success ++; //成功+1
   }
  }

  //将图片已json形式返回给js处理页面 ,这里大家可以改成自己的json返回处理代码
  echo json_encode(array(
   'total' => count($files),
   'success' => $success,
   'files' => $files,
  ));
 }
}
/*********************************分割*************************************************/
//这里我附上ensure_writable_dir()函数的代码
/**
* 确保文件夹存在并可写
*
* @param string $dir
*/
function ensure_writable_dir($dir) {
 if(!file_exists($dir)) {
  mkdir($dir, 0766, true);
  chmod($dir, 0766);
  chmod($dir, 0777);
 }
 else if(!is_writable($dir)) {
  chmod($dir, 0766);
  chmod($dir, 0777);
  if(!is_writable($dir)) {
   throw new FileSystemException("目录 $dir 不可写");
  }
 }
}

   代码基本上都加上了注释,方便大家理解,虽然是用PHP处理图片上传,但你理解了上传时程序代码所处理的逻辑思路,将思路用于.net或者java里都还是可以的。 

   以上就是使用JQuery插件ajaxFileUpload 异步上传文件的整一个分析过程,希望对大家的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to modify array elements in PHP?How to modify array elements in PHP?May 15, 2025 pm 08:21 PM

Methods to modify array elements in PHP include direct assignment and batch modification using functions. 1. For indexed arrays, such as $colors=['red','green','blue'], the second element can be modified by $colors[1]='yellow'. 2. For associative arrays, such as $person=['name'=>'John','age'=>30], the value of age can be modified by $person['age']=31. 3. Use array_map or array_walk functions to modify array elements in batches, such as $numbers=array_map(fun

How to implement hook function in PHP?How to implement hook function in PHP?May 15, 2025 pm 08:18 PM

Implementing hook functions in PHP can be implemented through observer mode or event-driven programming. The specific steps are as follows: 1. Create a HookManager class to register and trigger hooks. 2. Use the registerHook method to register the hook and trigger the hook by the triggerHook method when needed. Hook functions can improve the scalability and flexibility of the code, but pay attention to performance overhead and debugging complexity.

PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment