PHP combines the jQuery plug-in ajaxFileUpload to implement asynchronous file upload examples, _PHP tutorial

WBOY
Release: 2016-07-12 09:04:01
Original
974 people have browsed it

PHP combines with the jQuery plug-in ajaxFileUpload to implement an example of asynchronous file upload.

The most commonly used JQuery image upload plug-in is the Uploadify plug-in. The effect is very good, but it is not supported by mobile phones. flash, so I had to find another file upload plug-in to use. Later I found that the ajaxFileUpload plug-in is quite good, so I used this plug-in to achieve the effect of asynchronously uploading files. There are also many articles on the use of the ajaxFileUpload plug-in on the Internet, but I found that there is no PHP version, so this time the processing on the server side is handled in PHP language.

1. Detailed explanation of the syntax parameters of the ajaxFileUpload plug-in

 Principle: ajaxfileupload is implemented by monitoring the onload method of the iframe. When the processing from the server is completed, the onload event of the iframe is triggered to call its bound method. In the binding method, obtain the data body returned by the server in the iframe (supported ordinary text, json, xml, script, html)

 Syntax: $.ajaxFileUpload([options])

2. Next, let’s see how to use it

1. First introduce the ajaxFileUpload plug-in.

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

I am using the jq1.11.1 version here. It is said on the Internet that the jq version and the ajaxfileupload version must correspond so that there will be no abnormal errors. Anyway, I have no errors now.

2. Paste the HTML code.

  <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> 
Copy after login

The main thing here is the code of . Don’t worry about the other ones, because I am on the mobile phone here. The jqueryMobile plug-in is used.

3. Go to the js code for processing.

$(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="'+url+'" value="'+url+'" style="width:80%" >');
   //$('.upload-box').remove();
  },
  error: function(data, status, e){ //提交失败自动执行的处理函数
   alert(e);
  }
 })
});
Copy after login

Here I basically write comments on each line of code for everyone to understand. The process is to upload the image to uploader.php for processing. If the processing is successful, the json data will be returned. Then the url value will be taken out of the json, assigned to the img tag, and then the img tag will be appended to the page for display.

Here I attach the data returned by 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
  }
 ]
}
Copy after login

The HTML page before uploading looks like this:

After the asynchronous upload is successful, the HTML page will look like this:

 

4. See how PHP handles it

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 不可写");
  }
 }
}

Copy after login

The code is basically annotated to make it easier for everyone to understand. Although PHP is used to process image uploads, if you understand the logical ideas processed by the program code when uploading, you can still use the ideas in .net or java. of.

The above is the entire analysis process of asynchronously uploading files using the JQuery plug-in ajaxFileUpload. I hope it will be helpful to everyone's learning.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1075084.htmlTechArticlePHP combines the jQuery plug-in ajaxFileUpload to implement asynchronous file upload examples. The most commonly used JQuery image upload plug-in is Uploadify. Plug-in, the effect is very good, but because the mobile phone does not...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template