PHP结合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/imghw/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) ? 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 异步上传文件的整一个分析过程,希望对大家的学习有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:
