您好,欢迎访问一九零五行业门户网

JQ插件ajaxFileUpload、php实现图片,数据同时上传 ajaxfileupload乱码 ajaxfileupload ie8 ajaxfileupload ie

代码结构如下:
1、html代码,没必要解释了。
1doctype html> 2html> 3head> 4meta charset=utf-8> 5title>文件上传title> 6script src=http://libs.baidu.com/jquery/2.0.0/jquery.min.js>script> 7script src=uploads/ajaxfileupload.js type=text/javascript charset=utf-8>script> 8script type=text/javascript> 9 $(function(){10 $('#ti').click(function(){11var data = { name: 'my name', description: 'short description' } 12 $.ajaxfileupload({13 url: 'up.php',14 secureuri: false,15 data: data,16 fileelementid: 'upf',17 datatype: 'json',18 success: function (data) {19// var datejson=eval(data);20//console.log(data[0].path_name)21 $('#im').append(''+data%5b0%5d.path_name+'>') 22//console.log('')23 },24 error: function (data) {25 console.log(data)26 }27 });2829 })3031 })32script>33head>34body>3537input type=file name=upfm id=upf value=/>38input id='ti' type=button value=提交/>3940div id=im>4142div>4344body>4546html>
2、关于ajaxfileupload插件,在下面代码中如果你使用的是jq1.9以上请复制1-12到你的ajaxfileupload代码中,jq在很早就废弃了handleerror方法。注释关于代码的解释很清楚。
1jquery.extend({ 2 handleerror: function( s, xhr, status, e ) { 3 4if ( s.error ) { 5 s.error.call( s.context || s, xhr, status, e ); 6 } 7 8 9if ( s.global ) { 10 (s.context ? jquery(s.context) : jquery.event).trigger( ajaxerror, [xhr, s, e] ); 11 } 12 }, 13 createuploadiframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数 14//create frame 15var frameid = 'juploadframe' + id; //给iframe添加一个独一无二的id 16var iframehtml = '//创建iframe元素 17if (window.activexobject) {//判断浏览器是否支持activex控件 18if (typeof uri == 'boolean') { 19 iframehtml += ' src=' + 'javascript:false' + ''; 20 } elseif (typeof uri == 'string') { 21 iframehtml += ' src=' + uri + ''; 22 } 23 } 24 iframehtml += ' />'; 25 jquery(iframehtml).appendto(document.body); //将动态iframe追加到body中 26return jquery('#' + frameid).get(0); //返回iframe对象 27 }, 28 createuploadform: function (id, fileelementid, data) {//id为当前系统时间字符串,fileelementid为页面的id,data的值需要根据传入json的键来决定 29//create form 30var formid = 'juploadform' + id; //给form添加一个独一无二的id 31var fileid = 'juploadfile' + id; //给添加一个独一无二的id 32var form = jquery(''); //创建form元素 33if (data) {//通常为false 34for (var i in data) { 35 jquery('').appendto(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。 36 } 37 } var oldelement = jquery('#' + fileelementid); //得到页面中的对象 38var newelement = jquery(oldelement).clone(); //克隆页面中的对象 39 jquery(oldelement).attr('id', fileid); //修改原对象的id 40 jquery(oldelement).before(newelement); //在原对象前插入克隆对象 41 jquery(oldelement).appendto(form); //把原对象插入到动态form的结尾处 42//set attributes 43 jquery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来, 44 jquery(form).css('top', '-1200px'); 45 jquery(form).css('left', '-1200px'); 46 jquery(form).appendto('body'); //把动态form插入到body中 47return form; 48 }, 49 ajaxfileupload: function (s) {//这里s是个json对象,传入一些ajax的参数 50// todo introduce global settings, allowing the client to modify them for all requests, not only timeout 51 s = jquery.extend({}, jquery.ajaxsettings, s); //此时的s对象是由jquery.ajaxsettings和原s对象扩展后的对象 52var id = new date().gettime(); //取当前系统时间,目的是得到一个独一无二的数字 53var form = jquery.createuploadform(id, s.fileelementid, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form 54var io = jquery.createuploadiframe(id, s.secureuri); //创建动态iframe 55var frameid = 'juploadframe' + id; //动态iframe的id 56var formid = 'juploadform' + id; //动态form的id 57// watch for a new set of requests 58if (s.global && !jquery.active++) {//当jquery开始一个ajax请求时发生 59 jquery.event.trigger(ajaxstart); //触发ajaxstart方法 60 } var requestdone = false; //请求完成标志 61// create the request object 62var xml = {}; if (s.global) 63 jquery.event.trigger(ajaxsend, [xml, s]); //触发ajaxsend方法 64// wait for a response to come back 65var uploadcallback = function (istimeout) {//回调函数 66var io = document.getelementbyid(frameid); //得到iframe对象 67try { if (io.contentwindow) {//动态iframe所在窗口对象是否存在 68 xml.responsetext = io.contentwindow.document.body ? io.contentwindow.document.body.innerhtml : null; 69 xml.responsexml = io.contentwindow.document.xmldocument ? io.contentwindow.document.xmldocument : io.contentwindow.document; 70 } elseif (io.contentdocument) {//动态iframe的文档对象是否存在 71 xml.responsetext = io.contentdocument.document.body ? io.contentdocument.document.body.innerhtml : null; 72 xml.responsexml = io.contentdocument.document.xmldocument ? io.contentdocument.document.xmldocument : io.contentdocument.document; 73 } 74 } catch (e) { 75 jquery.handleerror(s, xml, null, e); 76 } if (xml || istimeout == timeout) {//xml变量被赋值或者istimeout == timeout都表示请求发出,并且有响应 77 requestdone = true; //请求完成 78var status; try { 79 status = istimeout != timeout ? success : error; //如果不是“超时”,表示请求成功 80// make sure that the request was successful or notmodified 81if (status != error) { // process the data (runs the xml through httpdata regardless of callback) 82var data = jquery.uploadhttpdata(xml, s.datatype); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果 83// if a local callback was specified, fire it and pass it the data 84if (s.success) 85 s.success(data, status); //执行上传成功的操作 86// fire the global callback 87if (s.global) 88 jquery.event.trigger(ajaxsuccess, [xml, s]); 89 } else 90 jquery.handleerror(s, xml, status); 91 } catch (e) { 92 status = error; 93 jquery.handleerror(s, xml, status, e); 94 } // the request was completed 95if (s.global) 96 jquery.event.trigger(ajaxcomplete, [xml, s]); // handle the global ajax counter 97if (s.global && ! --jquery.active) 98 jquery.event.trigger(ajaxstop); // process result 99if (s.complete)100 s.complete(xml, status);101 jquery(io).unbind();//移除iframe的事件处理程序102 settimeout(function () {//设置超时时间103try {104 jquery(io).remove();//移除动态iframe105 jquery(form).remove();//移除动态form106 } catch (e) {107 jquery.handleerror(s, xml, null, e);108 }109 }, 100)110 xml = null111 }112 } // timeout checker113if (s.timeout > 0) {//超时检测114 settimeout(function () { // check to see if the request is still happening115if (!requestdone) uploadcallback(timeout);//如果请求仍未完成,就发送超时信号116 }, s.timeout);117 } try { var form = jquery('#' + formid);118 jquery(form).attr('action', s.url);//传入的ajax页面导向url119 jquery(form).attr('method', 'post');//设置提交表单方式120 jquery(form).attr('target', frameid);//返回的目标iframe,就是创建的动态iframe121if (form.encoding) {//选择编码方式122 jquery(form).attr('encoding', 'multipart/form-data');123 } else {124 jquery(form).attr('enctype', 'multipart/form-data');125 }126 jquery(form).submit();//提交form表单127 } catch (e) {128 jquery.handleerror(s, xml, null, e);129 }130 jquery('#' + frameid).load(uploadcallback); //ajax 请求从服务器加载数据,同时传入回调函数131return { abort: function () { } };132 },133 uploadhttpdata: function (r, type) { var data = !type;134 data = type == xml || data ? r.responsexml : r.responsetext; // if the type is script, eval it in global context135if (type == script)136 jquery.globaleval(data); // get the javascript object, if json is used.137if (type == json)138 eval(data = + data); // evaluate scripts within html139if (type == html)140 jquery().html(data).evalscripts(); return data;141 }142 })3。php代码
1 php 2//print_r($_files); 3//echo json_encode(print_r($_files)); 4 5/** 6 * 生成唯一字符串 7 * @return string 8*/ 9function getuniname(){ 10returnmd5(uniqid(microtime(true),true)); 11} 12 13/** 14 * 得到文件的扩展名 15 * @param string $filename 16 * @return string 17*/ 18function getext($filename){ 19returnstrtolower(end(explode(.,$filename))); 20} 21 22/** 23 * 构建上传文件信息 24 * @return array 25*/ 26 27function buildinfo(){ 28if(!$_files){ 29return ; 30 } 31$i=0; 32foreach($_filesas$v){ 33//单文件 34if(is_string($v['name'])){ 35$files[$i]=$v; 36$i++; 37 }else{ 38//多文件 39foreach($v['name'] as$key=>$val){ 40$files[$i]['name']=$val; 41$files[$i]['size']=$v['size'][$key]; 42$files[$i]['tmp_name']=$v['tmp_name'][$key]; 43$files[$i]['error']=$v['error'][$key]; 44$files[$i]['type']=$v['type'][$key]; 45$i++; 46 } 47 } 48 } 49return$files; 50} 51function uploadfile($path=uploads,$allowext=array(gif,jpeg,png,jpg,wbmp),$maxsize=2097152,$imgflag=true){ 52if(!file_exists($path)){//判断是否有$path文件夹,没有则创建 53mkdir($path,0777,true);//0777表示最大权限 54 } 55$i=0; 56$files=buildinfo(); 57if(!($files&&is_array($files))){ 58return ; 59 } 60foreach($filesas$file){ 61if($file['error']===upload_err_ok){//就是0 62$ext=getext($file['name']); 63//检测文件的扩展名 64if(!in_array($ext,$allowext)){ 65exit(非法文件类型); 66 } 67//校验是否是一个真正的图片类型 68if($imgflag){ 69if(!getimagesize($file['tmp_name'])){ 70exit(不是真正的图片类型); 71 72 }else{ 73$file[filesize]=getimagesize($file['tmp_name']); 74//把文件信息付给$file 传到前台返回时数组 75 //如 [720, 1280, 2, width=720 height=1280, 8, 3, image/jpeg] 76 } 77 } 78//上传文件的大小 79if($file['size']>$maxsize){ 80exit(上传文件过大); 81 } 82if(!is_uploaded_file($file['tmp_name'])){ 83exit(不是通过http post方式上传上来的); 84 } 85$filename=getuniname()...$ext;//改文件重新命名 86$destination=$path./.$filename; 87if(move_uploaded_file($file['tmp_name'], $destination)){ 88$file['name']=$filename; 89$file['path_name']=$destination; 90unset($file['tmp_name'],$file['size'],$file['type']);//去除不需要传给的信息 91$uploadedfiles[$i]=$file; 92$i++; 93 } 94 }else{ 95switch($file['error']){ 96case 1: 97$mes=超过了配置文件上传文件的大小;//upload_err_ini_size 98break; 99case 2:100$mes=超过了表单设置上传文件的大小; //upload_err_form_size101break;102case 3:103$mes=文件部分被上传;//upload_err_partial104break;105case 4:106$mes=没有文件被上传1111;//upload_err_no_file107break;108case 6:109$mes=没有找到临时目录;//upload_err_no_tmp_dir110break;111case 7:112$mes=文件不可写;//upload_err_cant_write;113break;114case 8:115$mes=由于php的扩展程序中断了文件上传;//upload_err_extension116break;117 }118echo$mes;119 }120 }121return$uploadedfiles;122};123124$rows=uploadfile($path=uploads,$allowext=array(gif,jpeg,png,jpg,wbmp),$maxsize=2097152,$imgflag=true);125126echo json_encode($rows);
uploadfile($path=uploads,$allowext=array(gif,jpeg,png,jpg,wbmp),$maxsize=2097152,$imgflag=true);
这段php代码可以更改的可以上传其他文件和大小限制。getimagesize是判断是否为病毒文件更改后缀。
上述代码直接复制即可完成图片和用户数据的同时上传。
返回结果:[{name:d032a4ee7e957d956c8af0039d7e3085.jpg,error:0,filesiz:{0:720,1:1280,2:2,3:width=\720\ height=\1280\,bits:8,channels:3,mime:image\/jpeg},path_name:uploads\/d032a4ee7e957d956c8af0039d7e3085.jpg}]
以上就介绍了jq插件ajaxfileupload、php实现图片,数据同时上传,包括了ajaxfileupload方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息