加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajaxFileUpload.js 无刷新上传图片,支持多个参数同时上传,支持

发布时间:2020-12-15 21:38:23 所属栏目:百科 来源:网络整理
导读:ajaxFileUpload 无刷新上传的原理: 在页面动态创建 form 表单和 ifram 贞,设定 form 表单提交的目标为 ifram 贞, 将文件域和要 post 的参数动态写入 form 表单中,然后提交 from 表单。 通过 window.attachEvent 向 ifram 贞的 onload 事件中注册监听事件

ajaxFileUpload 无刷新上传的原理:

在页面动态创建 form 表单和 ifram 贞,设定 form 表单提交的目标为 ifram 贞,
将文件域和要 post 的参数动态写入 form 表单中,然后提交 from 表单。
通过 window.attachEvent 向 ifram 贞的 onload 事件中注册监听事件响应回调函数。

1.html 部分


[html]view plaincopy

  1. <inputname="imgfile1"id="imgfile1"style="width:200px;height:25px;"size="38"type="file"/>

  2. divid="imgContainer1"></div>


2.调用部分



[javascript]copy

  1. functionuploadImg(imgfileId,imgcontainerId){

  2. $.ajaxFileUpload({

  3. fileElementId:imgfileId,

  4. url:'/UploadImage',

  5. dataType:'json',

  6. data:{id:'aaa',name:'bbb'},

  7. beforeSend:function(XMLHttpRequest){

  8. //("loading");

  9. },

  10. success:function(data,textStatus){

  11. varimg="<imgsrc=''width='300'height='300'/>";

  12. $("#"+imgcontainerId).append(img);

  13. },

  14. error:function(XMLHttpRequest,textStatus,errorThrown){

  15. varimg="图片上传失败!";

  16. $("#"+imgcontainerId).append(img);

  17. varmsg="服务器出错,错误内容:"+XMLHttpRequest.responseText;

  18. $.messager.showWin({msg:msg,title:'错误提示',color:'red'});

  19. },

  20. complete://("loaded");

  21. }

  22. });

  23. }


3.ajaxFileUpload.js 全部代码

  • /*

  • 131108-xxj-ajaxFileUpload.js无刷新上传图片jquery插件,支持ie6-ie10

  • 依赖:jquery-1.6.1.min.js

  • 主方法:ajaxFileUpload接受json对象参数

  • 参数说明:

  • fileElementId:必选,上传文件域ID

  • url:必选,发送请求的URL字符串

  • fileFilter:可选,限定上传文件的格式(.jpg,.bmp,.gif,.png)

  • fileSize:可选,0为无限制(IE浏览器不兼容)

  • data:可选,将和文件域一同post的参数(json对象)

  • 其它:$.ajax的参数均为可选参数

  • 注:如遇到‘无法访问’的脚本错误提示则需要在响应流中加一段脚块一同输出:<script...>document.domain='xxx.com';</script>

  • */

  • jQuery.extend({

  • //创建iframe元素,接受提交及响应

  • createUploadIframe:function(id,uri){

  • //createframe

  • varframeId='jUploadFrame'+id;

  • if(window.ActiveXObject){

  • //fixie9andie10-------------

  • if(jQuery.browser.version=="9.0"||jQuery.browser.version=="10.0"){

  • vario=document.createElement('iframe');

  • io.id=frameId;

  • io.name=frameId;

  • }elseif(jQuery.browser.version=="6.0"||jQuery.browser.version=="7.0"||jQuery.browser.version=="8.0"){

  • vario=document.createElement('<iframeid="'+frameId+'"name="'+frameId+'"/>');

  • if(typeofuri=='boolean'){

  • io.src='javascript:false';

  • }typeofuri=='string'){

  • io.src=uri;

  • }

  • }

  • }else{

  • vario=document.createElement('iframe');

  • io.id=frameId;

  • io.name=frameId;

  • }

  • io.style.position='absolute';

  • io.style.top='-1000px';

  • io.style.left='-1000px';

  • document.body.appendChild(io);

  • returnio;

  • },

  • //创建from元素,用于提交的表单

  • createUploadForm://createform<spanstyle="white-space:pre"></span>

  • varformId='jUploadForm'+id;

  • varfileId='jUploadFile'+id;

  • varform=$('<formaction=""method="POST"name="'+formId+'"id="'+formId+'"enctype="multipart/form-data"></form>');

  • varoldElement=$('#'+fileElementId);

  • varnewElement=$(oldElement).clone();

  • $(oldElement).attr('id',fileId);

  • $(oldElement).before(newElement);

  • $(oldElement).appendTo(form);

  • //添加自定义参数

  • if(postData){

  • //递归遍历JSON所有键值

  • functionrecurJson(json){

  • for(variinjson){

  • //alert(i+"="+json[i])

  • $("<inputname='"+i+"'id='"+i+"'value='"+json[i]+"'/>").appendTo(form);

  • typeofjson[i]=="object"){

  • recurJson(json[i]);

  • }

  • }

  • }

  • recurJson(postData);

  • }

  • //setattributes

  • $(form).css('position','absolute');

  • $(form).css('top','-1200px');

  • $(form).css('left','-1200px');

  • $(form).appendTo('body');

  • returnform;

  • },0);background-color:inherit;">//上传文件

  • //s参数:json对象

  • ajaxFileUpload:function(s){

  • s=jQuery.extend({fileFilter:"",fileSize:0},jQuery.ajaxSettings,s);

  • //文件筛选

  • varfielName=$('#'+s.fileElementId).val();

  • varextention=fielName.substring(fielName.lastIndexOf(".")+1).toLowerCase();

  • if(s.fileFilter&&s.fileFilter.indexOf(extention)<0){

  • alert("仅支持("+s.fileFilter+")为后缀名的文件!");

  • return;

  • }

  • //文件大小限制

  • if(s.fileSize>0){

  • varfs=0;

  • try{

  • //IE浏览器

  • varimage=newImage();

  • image.dynsrc=fielName;

  • fs=image.fileSize;

  • }else{

  • fs=$('#'+s.fileElementId)[0].files[0].size;

  • }

  • }catch(e){

  • }

  • if(fs>s.fileSize){

  • alert("当前文件大小("+fs+")超过允许的限制值("+s.fileSize+")!");

  • return;

  • }

  • }

  • varid=newDate().getTime();

  • //创建form表单元素

  • varform=jQuery.createUploadForm(id,s.fileElementId,s.data);

  • //创建iframe贞元素

  • vario=jQuery.createUploadIframe(id,s.secureuri);

  • varframeId='jUploadFrame'+id;

  • varformId='jUploadForm'+id;

  • //监测是否有新的请求

  • if(s.global&&!jQuery.active++){

  • jQuery.event.trigger("ajaxStart");//触发AJAX请求开始时执行函数。Ajax事件。

  • }

  • varrequestDone=false;

  • //创建请求对象

  • varxml={};

  • if(s.global)

  • jQuery.event.trigger("ajaxSend",[xml,s]);//触发AJAX请求发送前事件

  • //上载完成的回调函数

  • varuploadCallback=function(isTimeout){

  • vario=document.getElementById(frameId);

  • try{

  • //存在跨域脚本访问问题,如遇到‘无法访问’提示则需要在响应流中加一段脚块:<script...>document.domain='xxx.com';</script>

  • if(io.contentWindow){//兼容各个浏览器,可取得子窗口的window对象

  • xml.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;

  • xml.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

  • }if(io.contentDocument){//contentDocumentFirefox支持,>ie8的ie支持。可取得子窗口的document对象。

  • xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;

  • xml.responseXML=io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;

  • }

  • }catch(e){

  • jQuery.handleErrorExt(s,xml,null,e);

  • }

  • if(xml||isTimeout=="timeout"){

  • requestDone=true;

  • varstatus;

  • try{

  • status=isTimeout!="timeout"?"success":"error";

  • //Makesurethattherequestwassuccessfulornotmodified

  • if(status!="error"){

  • //处理数据(运行XML通过httpData不管回调)

  • vardata=jQuery.uploadHttpData(xml,s.dataType);

  • //Ifalocalcallbackwasspecified,fireitandpassitthedata

  • if(s.success)

  • s.success(data,status);

  • //Firetheglobalcallback

  • if(s.global)

  • jQuery.event.trigger("ajaxSuccess",s]);

  • }else

  • jQuery.handleErrorExt(s,status);

  • }catch(e){

  • status="error";

  • jQuery.handleErrorExt(s,status,e);

  • }

  • //Therequestwascompleted

  • if(s.global)

  • jQuery.event.trigger("ajaxComplete",s]);

  • //HandletheglobalAJAXcounter

  • if(s.global&&!--jQuery.active)

  • jQuery.event.trigger("ajaxStop");

  • //Processresult

  • if(s.complete)

  • s.complete(xml,status);

  • jQuery(io).unbind();

  • setTimeout(function(){

  • try{

  • $(io).remove();

  • $(form).remove();

  • }}

  • },100);

  • xml=null;

  • }

  • };

  • //超时检查,s.timeout毫秒后调用uploadCallback回调函数提示请求超时

  • if(s.timeout>0){

  • setTimeout(function(){

  • //Checktoseeiftherequestisstillhappening

  • if(!requestDone)uploadCallback("timeout");

  • },s.timeout);

  • }

  • //设置动态form表单的提交参数

  • //vario=$('#'+frameId);

  • varform=$('#'+formId);

  • $(form).attr('action',s.url);

  • $(form).attr('method','POST');

  • $(form).attr('target',frameId);

  • if(form.encoding){

  • form.encoding='multipart/form-data';

  • }else{

  • form.enctype='multipart/form-data';

  • }

  • $(form).submit();

  • }}

  • //向动态表单的页面加载事件中注册回调函数

  • if(window.attachEvent){

  • document.getElementById(frameId).attachEvent('onload',uploadCallback);

  • }else{

  • document.getElementById(frameId).addEventListener('load',uploadCallback,false);

  • }

  • return{

  • abort:function(){

  • }

  • };

  • },0);background-color:inherit;">//上传文件

  • uploadHttpData:function(r,type){

  • //alert("type="+type+";uploadHttpData"+JSON.stringify(r))

  • vardata=!type;

  • data=type=="xml"||data?r.responseXML:r.responseText;

  • //Ifthetypeis"script",evalitinglobalcontext

  • if(type=="script")

  • jQuery.globalEval(data);

  • //GettheJavaScriptobject,ifJSONisused.

  • if(type=="json")

  • eval("data="+data);

  • //evaluatescriptswithinhtml

  • if(type=="html")

  • jQuery("<div>").html(data).evalScripts();

  • //alert($('param',data).each(function(){alert($(this).attr('value'));}));

  • returndata;

  • },

  • handleErrorExt:function(s,xhr,e){

  • if(s.error){

  • s.error.call(s.context||s,153);font-weight:bold;background-color:inherit;">if(s.global){

  • (s.context?jQuery(s.context):jQuery.event).trigger("ajaxError",[xhr,s,e]);

  • }

  • }

  • });

  • (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读