AjaxUpLoad.js使用实现文件上传

前端之家收集整理的这篇文章主要介绍了AjaxUpLoad.js使用实现文件上传前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

AjaxUpLoad.js的使用实现无刷新文件上传,如图。

图1 文件上传

图2 文件上传

1、创建页面并编写HTML

[html] view plain copy
  1. 上传文档:
  2. <divclass="uploadFile">
  3. <spanid="doc"><inputtype="text"disabled="disabled"/></span>
  4. <inputtype="hidden"id="hidFileName"/>
  5. <inputtype="button"id="btnUploadFile"value="上传"/>
  6. <inputtype="button"id="btnDeleteFile"value="删除"/>
  7. </div>
  8. 上传图片:
  9. <divclass="uploadImg">
  10. <imgid="imgShow"src="/images/nophoto.gif"/>
  11. <inputtype="hidden"id="hidImgName"/>
  12. <inputtype="button"id="btnUploadImg"value="上传"/>
  13. <inputtype="button"id="btnDeleteImg"value="删除"/>
  14. </div>

2、引用AjaxUpload.js文件

[html] view plain copy
  1. <scriptsrc="/js/common/AjaxUpload.js"type="text/javascript"></script>

3、编写JS脚本

[java] view plain copy
@H_708_502@
  1. window.onload=function(){
  2. init();//初始化
  3. }
  4. //初始化
  5. functioninit(){
  6. //初始化文档上传
  7. varbtnFile=document.getElementById("btnUploadFile");
  8. vardoc=document.getElementById("doc");
  9. varhidFileName=document.getElementById("hidFileName");
  10. document.getElementById("btnDeleteFile").onclick=function(){DelFile(doc,hidFileName);};
  11. g_AjxUploadFile(btnFile,doc,hidFileName);
  12. //初始化图片上传
  13. varbtnImg=document.getElementById("btnUploadImg");
  14. varimg=document.getElementById("imgShow");
  15. varhidImgName=document.getElementById("hidImgName");
  16. document.getElementById("btnDeleteImg").onclick=function(){DelImg(img,hidImgName);};
  17. g_AjxUploadImg(btnImg,img,hidImgName);
  18. }
  19. varg_AjxTempDir="/file/temp/";
  20. //文档上传
  21. functiong_AjxUploadFile(btn,hidPut,action){
  22. varbutton=btn,interval;
  23. newAjaxUpload(button,{
  24. action:((action==null||action==undefined)?'/Common/UploadHandler.ashx?fileType=file':action),
  25. data:{},
  26. name:'myfile',
  27. onSubmit:function(file,ext){
  28. if(!(ext&&/^(rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|RAR|ZIP|PDF|PDFX|TXT|CSV|XLS|XLSX|DOC|DOCX)$/.test(ext))){
  29. alert("您上传的文档格式不对,请重新选择!");
  30. returnfalse;
  31. }
  32. },
  33. onComplete:function(file,response){
  34. flagValue=response;
  35. if(flagValue=="1"){
  36. alert("您上传的文档格式不对,请重新选择!");
  37. }
  38. elseif(flagValue=="2"){
  39. alert("您上传的文档大于2M,请重新选择!");
  40. }
  41. elseif(flagValue=="3"){
  42. alert("文档上传失败!");
  43. }
  44. else{
  45. hidPut.value=response;
  46. doc.innerHTML="<ahref='"+g_AjxTempDir+response+"'target='_blank'>"+response+"</a>";
  47. }
  48. }
  49. });
  50. }
  51. //图片上传
  52. functiong_AjxUploadImg(btn,hidPut){
  53. varbutton=btn,{
  54. action:'/Common/UploadHandler.ashx?fileType=img',
  55. data:{},ext){
  56. if(!(ext&&/^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))){
  57. alert("您上传图片格式不对,请重新选择!");
  58. returnfalse;
  59. }
  60. },response){
  61. flagValue=response;
  62. if(flagValue=="1"){
  63. alert("您上传图片格式不对,请重新选择!");
  64. }
  65. elseif(flagValue=="2"){
  66. alert("您上传图片大于200K,请重新选择!");
  67. }
  68. elseif(flagValue=="3"){
  69. alert("图片上传失败!");
  70. }
  71. else{
  72. hidPut.value=response;
  73. img.src=g_AjxTempDir+response;
  74. }
  75. }
  76. });
  77. }
  78. //删除文档
  79. functionDelFile(doc,hidPut){
  80. hidPut.value="";
  81. doc.innerHTML="<inputtype=\"text\"disabled=\"disabled\"/>";
  82. }
  83. //删除图片
  84. functionDelImg(img,hidPut){
  85. hidPut.value="";
  86. img.src="/images/nophoto.gif";
  87. }

4、创建/Common/UploadHandler.ashx处理程序

[csharp] view plain copy
  1. <%@WebHandlerLanguage="C#"Class="UploadHandler"%>
  2. usingSystem;
  3. usingSystem.Web;
  4. usingSystem.Text.RegularExpressions;
  5. usingSystem.IO;
  6. publicclassUploadHandler:IHttpHandler{
  7. privatestring_filedir="";//文件目录
  8. ///<summary>
  9. ///处理上传文件(1:文件格式不正确、2:文件大小不正确、3:上传失败、文件名称:上传成功)
  10. ///</summary>
  11. ///<paramname="context"></param>
  12. publicvoidProcessRequest(HttpContextcontext){
  13. _filedir=context.Server.MapPath(@"/file/temp/");
  14. try
  15. {
  16. stringresult="3";
  17. stringfileType=context.Request.QueryString["fileType"];//获取上传文件类型
  18. if(fileType=="file")
  19. {
  20. result=UploadFile(context);//文档上传
  21. }
  22. elseif(fileType=="img")
  23. {
  24. result=UploadImg(context);//图片上传
  25. }
  26. context.Response.Write(result);
  27. }
  28. catch
  29. {
  30. context.Response.Write("3");//3文件上传失败
  31. }
  32. }
  33. ///<summary>
  34. ///文档上传
  35. ///</summary>
  36. ///<paramname="context"></param>
  37. ///<returns></returns>
  38. privatestringUploadFile(HttpContextcontext)
  39. {
  40. intcout=context.Request.Files.Count;
  41. if(cout>0)
  42. {
  43. HttpPostedFilehpf=context.Request.Files[0];
  44. if(hpf!=null)
  45. {
  46. stringfileExt=Path.GetExtension(hpf.FileName).ToLower();
  47. //只能上传文件,过滤不可上传文件类型
  48. stringfileFilt=".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......";
  49. if(fileFilt.IndexOf(fileExt)<=-1)
  50. {
  51. return"1";
  52. }
  53. //判断文件大小
  54. intlength=hpf.ContentLength;
  55. if(length>2097152)
  56. {
  57. return"2";
  58. }
  59. Randomrd=newRandom();
  60. DateTimenowTime=DateTime.Now;
  61. stringnewFileName=nowTime.Year.ToString()+nowTime.Month.ToString()+nowTime.Day.ToString()+nowTime.Hour.ToString()+nowTime.Minute.ToString()+nowTime.Second.ToString()+rd.Next(1000,1000000)+Path.GetExtension(hpf.FileName);
  62. if(!Directory.Exists(_filedir))
  63. {
  64. Directory.CreateDirectory(_filedir);
  65. }
  66. stringfileName=_filedir+newFileName;
  67. hpf.SaveAs(fileName);
  68. returnnewFileName;
  69. }
  70. }
  71. return"3";
  72. }
  73. ///<summary>
  74. ///图片上传
  75. ///</summary>
  76. ///<paramname="context"></param>
  77. ///<returns></returns>
  78. privatestringUploadImg(HttpContextcontext)
  79. {
  80. intcout=context.Request.Files.Count;
  81. if(cout>0)
  82. {
  83. HttpPostedFilehpf=context.Request.Files[0];
  84. if(hpf!=null)
  85. {
  86. stringfileExt=Path.GetExtension(hpf.FileName).ToLower();
  87. //只能上传文件,过滤不可上传文件类型
  88. stringfileFilt=".gif|.jpg|.PHP|.jsp|.jpeg|.png|......";
  89. if(fileFilt.IndexOf(fileExt)<=-1)
  90. {
  91. return"1";
  92. }
  93. //判断文件大小
  94. intlength=hpf.ContentLength;
  95. if(length>204800)
  96. {
  97. return"2";
  98. }
  99. Randomrd=newRandom();
  100. DateTimenowTime=DateTime.Now;
  101. stringnewFileName=nowTime.Year.ToString()+nowTime.Month.ToString()+nowTime.Day.ToString()+nowTime.Hour.ToString()+nowTime.Minute.ToString()+nowTime.Second.ToString()+rd.Next(1000,1000000)+Path.GetExtension(hpf.FileName);
  102. if(!Directory.Exists(_filedir))
  103. {
  104. Directory.CreateDirectory(_filedir);
  105. }
  106. stringfileName=_filedir+newFileName;
  107. hpf.SaveAs(fileName);
  108. returnnewFileName;
  109. }
  110. }
  111. return"3";
  112. }
  113. #regionIHttpHandler成员
  114. publicboolIsReusable
  115. {
  116. get{thrownewNotImplementedException();}
  117. }
  118. #endregion
  119. }

附件1:页面CSS样式

  1. /*上传文件*/
  2. .uploadFile{margin-bottom:10px;}
  3. /*上传图片*/
  4. .uploadImg{}
  5. .uploadImgimg{width:102px;height:64px;border:1pxsolid#CCCCCC;display:block;}

附件2:AjaxUpload.js文件

[javascript] view plain copy
  1. /**
  2. *AJAXUpload(http://valums.com/ajax-upload/)
  3. *Copyright(c)AndrisValums
  4. *LicensedundertheMITlicense(http://valums.com/mit-license/)
  5. *ThankstoGaryHaran,DavidMark,CoreyBurnsandothersforcontributions
  6. */
  7. (function(){
  8. /*globalwindow*/
  9. /*jslintbrowser:true,devel:true,undef:true,nomen:true,bitwise:true,regexp:true,newcap:true,immed:true*/
  10. /**
  11. *WrapperforFireBug'sconsole.log
  12. */
  13. functionlog(){
  14. if(typeof(console)!='undefined'&&typeof(console.log)=='function'){
  15. Array.prototype.unshift.call(arguments,'[AjaxUpload]');
  16. console.log(Array.prototype.join.call(arguments,''));
  17. }
  18. }
  19. /**
  20. *Attacheseventtoadomelement.
  21. *@param{Element}el
  22. *@paramtypeeventname
  23. *@paramfncallbackThisreferstothepassedelement
  24. */
  25. functionaddEvent(el,type,fn){
  26. if(el.addEventListener){
  27. el.addEventListener(type,fn,false);
  28. }elseif(el.attachEvent){
  29. el.attachEvent('on'+type,function(){
  30. fn.call(el);
  31. });
  32. }else{
  33. thrownewError('notsupportedorDOMnotloaded');
  34. }
  35. }
  36. /**
  37. *Attachesresizeeventtoawindow,limiting
  38. *numberofeventfired.Firesonlywhenencounteres
  39. *delayof100afterseriesofevents.
  40. *
  41. *Somebrowsersfireeventmultipletimeswhenresizing
  42. *http://www.quirksmode.org/dom/events/resize.html
  43. *
  44. *@paramfncallbackThisreferstothepassedelement
  45. */
  46. functionaddResizeEvent(fn){
  47. vartimeout;
  48. addEvent(window,'resize',function(){
  49. if(timeout){
  50. clearTimeout(timeout);
  51. }
  52. timeout=setTimeout(fn,100);
  53. });
  54. }
  55. //Needsmoretesting,willberewritenfornextversion
  56. //getOffsetfunctioncopiedfromjQuerylib(http://jquery.com/)
  57. if(document.documentElement.getBoundingClientRect){
  58. //GetOffsetusinggetBoundingClientRect
  59. //http://ejohn.org/blog/getboundingclientrect-is-awesome/
  60. vargetOffset=function(el){
  61. varBox=el.getBoundingClientRect();
  62. vardoc=el.ownerDocument;
  63. varbody=doc.body;
  64. vardocElem=doc.documentElement;//forie
  65. varclientTop=docElem.clientTop||body.clientTop||0;
  66. varclientLeft=docElem.clientLeft||body.clientLeft||0;
  67. //InInternetExplorer7getBoundingClientRectpropertyistreatedasphysical,
  68. //whileothersarelogical.Makealllogical,likeinIE8.
  69. varzoom=1;
  70. if(body.getBoundingClientRect){
  71. varbound=body.getBoundingClientRect();
  72. zoom=(bound.right-bound.left)/body.clientWidth;
  73. }
  74. if(zoom>1){
  75. clientTop=0;
  76. clientLeft=0;
  77. }
  78. vartop=Box.top/zoom+(window.pageYOffset||docElem&&docElem.scrollTop/zoom||body.scrollTop/zoom)-clientTop,
  79. left=Box.left/zoom+(window.pageXOffset||docElem&&docElem.scrollLeft/zoom||body.scrollLeft/zoom)-clientLeft;
  80. return{
  81. top:top,
  82. left:left
  83. };
  84. };
  85. }else{
  86. //Getoffsetaddingalloffsets
  87. vargetOffset=function(el){
  88. vartop=0,
  89. left=0;
  90. do{
  91. top+=el.offsetTop||0;
  92. left+=el.offsetLeft||0;
  93. el=el.offsetParent;
  94. }while(el);
  95. return{
  96. left:left,
  97. top:top
  98. };
  99. };
  100. }
  101. /**
  102. *Returnsleft,top,rightandbottompropertiesdescribingtheborder-Box,
  103. *inpixels,withthetop-leftrelativetothebody
  104. *@param{Element}el
  105. *@return{Object}Containsleft,right,bottom
  106. */
  107. functiongetBox(el){
  108. varleft,bottom;
  109. varoffset=getOffset(el);
  110. left=offset.left;
  111. top=offset.top;
  112. right=left+el.offsetWidth;
  113. bottom=top+el.offsetHeight;
  114. return{
  115. left:left,
  116. right:right,
  117. top:top,
  118. bottom:bottom
  119. };
  120. }
  121. /**
  122. *Helperthattakesobjectliteral
  123. *andaddallpropertiestoelement.style
  124. *@param{Element}el
  125. *@param{Object}styles
  126. */
  127. functionaddStyles(el,styles){
  128. for(varnameinstyles){
  129. if(styles.hasOwnProperty(name)){
  130. el.style[name]=styles[name];
  131. }
  132. }
  133. }
  134. /**
  135. *Functionplacesanabsolutelypositioned
  136. *elementontopofthespecifiedelement
  137. *copyingpositionanddimentions.
  138. *@param{Element}from
  139. *@param{Element}to
  140. */
  141. functioncopyLayout(from,to){
  142. varBox=getBox(from);
  143. addStyles(to,{
  144. position:'absolute',
  145. left:Box.left+'px',
  146. top:Box.top+'px',
  147. width:from.offsetWidth+'px',
  148. height:from.offsetHeight+'px'
  149. });
  150. }
  151. /**
  152. *Createsandreturnselementfromhtmlchunk
  153. *UsesinnerHTMLtocreateanelement
  154. */
  155. vartoElement=(function(){
  156. vardiv=document.createElement('div');
  157. returnfunction(html){
  158. div.innerHTML=html;
  159. varel=div.firstChild;
  160. returndiv.removeChild(el);
  161. };
  162. })();
  163. /**
  164. *Functiongeneratesuniqueid
  165. *@returnuniqueid
  166. */
  167. vargetUID=(function(){
  168. varid=0;
  169. returnfunction(){
  170. return'ValumsAjaxUpload'+id++;
  171. };
  172. })();
  173. /**
  174. *Getfilenamefrompath
  175. *@param{String}filepathtofile
  176. *@returnfilename
  177. */
  178. functionfileFromPath(file){
  179. returnfile.replace(/.*(\/|\\)/,"");
  180. }
  181. /**
  182. *Getfileextensionlowercase
  183. *@param{String}filename
  184. *@returnfileextenstion
  185. */
  186. functiongetExt(file){
  187. return(-1!==file.indexOf('.'))?file.replace(/.*[.]/,''):'';
  188. }
  189. functionhasClass(el,name){
  190. varre=newRegExp('\\b'+name+'\\b');
  191. returnre.test(el.className);
  192. }
  193. functionaddClass(el,name){
  194. if(!hasClass(el,name)){
  195. el.className+=''+name;
  196. }
  197. }
  198. functionremoveClass(el,name){
  199. varre=newRegExp('\\b'+name+'\\b');
  200. el.className=el.className.replace(re,'');
  201. }
  202. functionremoveNode(el){
  203. el.parentNode.removeChild(el);
  204. }
  205. /**
  206. *Easystylinganduploading
  207. *@constructor
  208. *@parambuttonAnelementyouwantconvertto
  209. *uploadbutton.Testeddimentionsupto500x500px
  210. *@param{Object}optionsSeedefaultsbelow.
  211. */
  212. window.AjaxUpload=function(button,options){
  213. this._settings={
  214. //Locationoftheserver-sideuploadscript
  215. action:'upload.PHP',
  216. //Fileuploadname
  217. name:'userfile',
  218. //Additionaldatatosend
  219. data:{},
  220. //Submitfileassoonasit'sselected
  221. autoSubmit:true,
  222. //Thetypeofdatathatyou'reexpectingbackfromtheserver.
  223. //htmlandxmlaredetectedautomatically.
  224. //Onlyusefulwhenyouareusingjsondataasaresponse.
  225. //Setto"json"inthatcase.
  226. responseType:false,
  227. //Classappliedtobuttonwhenmouseishovered
  228. hoverClass:'hover',
  229. //ClassappliedtobuttonwhenAUisdisabled
  230. disabledClass:'disabled',
  231. //Whenuserselectsafile,usefulwithautoSubmitdisabled
  232. //Youcanreturnfalsetocancelupload
  233. onChange:function(file,extension){},
  234. //Callbacktofirebeforefileisuploaded
  235. //Youcanreturnfalsetocancelupload
  236. onSubmit:function(file,
  237. //Firedwhenfileuploadiscompleted
  238. //WARNING!DONOTUSE"FALSE"STRINGASARESPONSE!
  239. onComplete:function(file,response){}
  240. };
  241. //Mergetheusersoptionswithourdefaults
  242. for(variinoptions){
  243. if(options.hasOwnProperty(i)){
  244. this._settings[i]=options[i];
  245. }
  246. }
  247. //buttonisn'tnecessaryadomelement
  248. if(button.jquery){
  249. //jQueryobjectwaspassed
  250. button=button[0];
  251. }elseif(typeofbutton=="string"){
  252. if(/^#.*/.test(button)){
  253. //IfjQueryuserpasses#elementIddon'tbreakit
  254. button=button.slice(1);
  255. }
  256. button=document.getElementById(button);
  257. }
  258. if(!button||button.nodeType!==1){
  259. thrownewError("Pleasemakesurethatyou'repassingavalidelement");
  260. }
  261. if(button.nodeName.toUpperCase()=='A'){
  262. //disablelink
  263. addEvent(button,'click',function(e){
  264. if(e&&e.preventDefault){
  265. e.preventDefault();
  266. }elseif(window.event){
  267. window.event.returnValue=false;
  268. }
  269. });
  270. }
  271. //DOMelement
  272. this._button=button;
  273. //DOMelement
  274. this._input=null;
  275. //Ifdisabledclickingonbuttonwon'tdoanything
  276. this._disabled=false;
  277. //ifthebuttonwasdisabledbeforerefreshifwillremain
  278. //disabledinFireFox,let'sfixit
  279. this.enable();
  280. this._rerouteClicks();
  281. };
  282. //assigningmethodstoourclass
  283. AjaxUpload.prototype={
  284. setData:function(data){
  285. this._settings.data=data;
  286. },
  287. disable:function(){
  288. addClass(this._button,this._settings.disabledClass);
  289. this._disabled=true;
  290. varnodeName=this._button.nodeName.toUpperCase();
  291. if(nodeName=='INPUT'||nodeName=='BUTTON'){
  292. this._button.setAttribute('disabled','disabled');
  293. }
  294. //hideinput
  295. if(this._input){
  296. //WeusevisibilityinsteadofdisplaytofixproblemwithSafari4
  297. //Theproblemisthatthevalueofinputdoesn'tchangeifit
  298. //hasdisplaynonewhenuserselectsafile
  299. this._input.parentNode.style.visibility='hidden';
  300. }
  301. },
  302. enable:function(){
  303. removeClass(this._button,this._settings.disabledClass);
  304. this._button.removeAttribute('disabled');
  305. this._disabled=false;
  306. },
  307. /**
  308. *Createsinvisiblefileinput
  309. *thatwillhoverabovethebutton
  310. *<div><inputtype='file'/></div>
  311. */
  312. _createInput:function(){
  313. varself=this;
  314. varinput=document.createElement("input");
  315. input.setAttribute('type','file');
  316. input.setAttribute('name',this._settings.name);
  317. addStyles(input,{
  318. 'position':'absolute',
  319. //inOperaonly'browse'button
  320. //isclickableanditislocatedat
  321. //therightsideoftheinput
  322. 'right':0,
  323. 'margin':0,
  324. 'padding':0,
  325. 'fontSize':'480px',
  326. 'cursor':'pointer'
  327. });
  328. vardiv=document.createElement("div");
  329. addStyles(div,{
  330. 'display':'block',
  331. 'position':'absolute',
  332. 'overflow':'hidden',
  333. 'margin':0,
  334. 'opacity':0,
  335. //Makesurebrowsebuttonisintherightside
  336. //inInternetExplorer
  337. 'direction':'ltr',
  338. //MaxzIndexsupportedbyOpera9.0-9.2
  339. 'zIndex':2147483583
  340. });
  341. //Makesurethatelementopacityexists.
  342. //OtherwiseuseIEfilter
  343. if(div.style.opacity!=="0"){
  344. if(typeof(div.filters)=='undefined'){
  345. thrownewError('Opacitynotsupportedbythebrowser');
  346. }
  347. div.style.filter="alpha(opacity=0)";
  348. }
  349. addEvent(input,'change',function(){
  350. if(!input||input.value===''){
  351. return;
  352. }
  353. //Getfilenamefrominput,required
  354. //assomebrowsershavepathinsteadofit
  355. varfile=fileFromPath(input.value);
  356. if(false===self._settings.onChange.call(self,file,getExt(file))){
  357. self._clearInput();
  358. return;
  359. }
  360. //Submitformwhenvalueischanged
  361. if(self._settings.autoSubmit){
  362. self.submit();
  363. }
  364. });
  365. addEvent(input,'mouSEOver',function(){
  366. addClass(self._button,self._settings.hoverClass);
  367. });
  368. addEvent(input,'mouSEOut',function(){
  369. removeClass(self._button,self._settings.hoverClass);
  370. //WeusevisibilityinsteadofdisplaytofixproblemwithSafari4
  371. //Theproblemisthatthevalueofinputdoesn'tchangeifit
  372. //hasdisplaynonewhenuserselectsafile
  373. input.parentNode.style.visibility='hidden';
  374. });
  375. div.appendChild(input);
  376. document.body.appendChild(div);
  377. this._input=input;
  378. },
  379. _clearInput:function(){
  380. if(!this._input){
  381. return;
  382. }
  383. //this._input.value='';Doesn'tworkinIE6
  384. removeNode(this._input.parentNode);
  385. this._input=null;
  386. this._createInput();
  387. removeClass(this._button,this._settings.hoverClass);
  388. },
  389. /**
  390. *Functionmakessurethatwhenuserclicksuploadbutton,
  391. *thethis._inputisclickedinstead
  392. */
  393. _rerouteClicks:function(){
  394. varself=this;
  395. //IEwilllaterdisplay'accessdenied'error
  396. //ifyouuseusingself._input.click()
  397. //otherbrowsersjustignoreclick()
  398. addEvent(self._button,function(){
  399. if(self._disabled){
  400. return;
  401. }
  402. if(!self._input){
  403. self._createInput();
  404. }
  405. vardiv=self._input.parentNode;
  406. copyLayout(self._button,div);
  407. div.style.visibility='visible';
  408. });
  409. //commentedbecausewenowhideinputonmouseleave
  410. /**
  411. *Whenthewindowisresizedtheelements
  412. *canbemisalignedifbuttonpositiondepends
  413. *onwindowsize
  414. */
  415. //addResizeEvent(function(){
  416. //if(self._input){
  417. //copyLayout(self._button,self._input.parentNode);
  418. //}
  419. //});
  420. },
  421. /**
  422. *Createsiframewithuniquename
  423. *@return{Element}iframe
  424. */
  425. _createIframe:function(){
  426. //Wecan'tusegetTime,becauseitsometimesreturn
  427. //samevalueinsafari:(
  428. varid=getUID();
  429. //Wecan'tusefollowingcodeasthenameattribute
  430. //won'tbeproperlyregisteredinIE6,andnewwindow
  431. //onformsubmitwillopen
  432. //variframe=document.createElement('iframe');
  433. //iframe.setAttribute('name',id);
  434. variframe=toElement('<iframesrc="javascript:false;"name="'+id+'"/>');
  435. //src="javascript:false;wasadded
  436. //becauseitpossiblyremovesie6prompt
  437. //"Thispagecontainsbothsecureandnonsecureitems"
  438. //Anyway,itdoesn'tdoanyharm.
  439. iframe.setAttribute('id',id);
  440. iframe.style.display='none';
  441. document.body.appendChild(iframe);
  442. returniframe;
  443. },
  444. /**
  445. *Createsform,thatwillbesubmittedtoiframe
  446. *@param{Element}iframeWheretosubmit
  447. *@return{Element}form
  448. */
  449. _createForm:function(iframe){
  450. varsettings=this._settings;
  451. //Wecan'tusethefollowingcodeinIE6
  452. //varform=document.createElement('form');
  453. //form.setAttribute('method','post');
  454. //form.setAttribute('enctype','multipart/form-data');
  455. //Becauseinthiscasefilewon'tbeattachedtorequest
  456. varform=toElement('<formmethod="post"enctype="multipart/form-data"></form>');
  457. form.setAttribute('action',settings.action);
  458. form.setAttribute('target',iframe.name);
  459. form.style.display='none';
  460. document.body.appendChild(form);
  461. //Createhiddeninputelementforeachdatakey
  462. for(varpropinsettings.data){
  463. if(settings.data.hasOwnProperty(prop)){
  464. varel=document.createElement("input");
  465. el.setAttribute('type','hidden');
  466. el.setAttribute('name',prop);
  467. el.setAttribute('value',settings.data[prop]);
  468. form.appendChild(el);
  469. }
  470. }
  471. returnform;
  472. },
  473. /**
  474. *GetsresponsefromiframeandfiresonCompleteeventwhenready
  475. *@paramiframe
  476. *@paramfileFilenametouseinonCompletecallback
  477. */
  478. _getResponse:function(iframe,file){
  479. //gettingresponse
  480. vartoDeleteFlag=false,
  481. self=this,
  482. settings=this._settings;
  483. addEvent(iframe,'load',function(){
  484. if(//ForSafari
  485. iframe.src=="javascript:'%3Chtml%3E%3C/html%3E';"||
  486. //ForFF,IE
  487. iframe.src=="javascript:'<html></html>';"){
  488. //Firsttimearound,donotdelete.
  489. //Wereloadtoblankpage,sothatreloadingmainpage
  490. //doesnotre-submitthepost.
  491. if(toDeleteFlag){
  492. //FixbusystateinFF3
  493. setTimeout(function(){
  494. removeNode(iframe);
  495. },
  496. 0);
  497. }
  498. return;
  499. }
  500. vardoc=iframe.contentDocument?iframe.contentDocument:window.frames[iframe.id].document;
  501. //fixingOpera9.26,10.00
  502. if(doc.readyState&&doc.readyState!='complete'){
  503. //Operafiresloadeventmultipletimes
  504. //EvenwhentheDOMisnotreadyyet
  505. //thisfixshouldnotaffectotherbrowsers
  506. return;
  507. }
  508. //fixingOpera9.64
  509. if(doc.body&&doc.body.innerHTML=="false"){
  510. //InOpera9.64eventwasfiredsecondtime
  511. //whenbody.innerHTMLchangedfromfalse
  512. //toserverresponseapprox.after1sec
  513. return;
  514. }
  515. varresponse;
  516. if(doc.XMLDocument){
  517. //responseisaxmldocumentInternetExplorerproperty
  518. response=doc.XMLDocument;
  519. }elseif(doc.body){
  520. //responseishtmldocumentorplaintext
  521. response=doc.body.innerHTML;
  522. if(settings.responseType&&settings.responseType.toLowerCase()=='json'){
  523. //Ifthedocumentwassentas'application/javascript'or
  524. //'text/javascript',thenthebrowserwrapsthetextina<pre>
  525. //tagandperformshtmlencodingonthecontents.Inthiscase,
  526. //weneedtopulltheoriginaltextcontentfromthetextnode's
  527. //nodeValuepropertytoretrievetheunmangledcontent.
  528. //NotethatIE6onlyunderstandstext/html
  529. if(doc.body.firstChild&&doc.body.firstChild.nodeName.toUpperCase()=='PRE'){
  530. response=doc.body.firstChild.firstChild.nodeValue;
  531. }
  532. if(response){
  533. response=eval("("+response+")");
  534. }else{
  535. response={};
  536. }
  537. }
  538. }else{
  539. //responseisaxmldocument
  540. response=doc;
  541. }
  542. settings.onComplete.call(self,response);
  543. //Reloadblankpage,sothatreloadingmainpage
  544. //doesnotre-submitthepost.Also,rememberto
  545. //deletetheframe
  546. toDeleteFlag=true;
  547. //FixIEmixedcontentissue
  548. iframe.src="javascript:'<html></html>';";
  549. });
  550. },
  551. /**
  552. *Uploadfilecontainedinthis._input
  553. */
  554. submit:function(){
  555. varself=this,
  556. settings=this._settings;
  557. if(!this._input||this._input.value===''){
  558. return;
  559. }
  560. varfile=fileFromPath(this._input.value);
  561. //userreturnedfalsetocancelupload
  562. if(false===settings.onSubmit.call(this,getExt(file))){
  563. this._clearInput();
  564. return;
  565. }
  566. //sendingrequest
  567. variframe=this._createIframe();
  568. varform=this._createForm(iframe);
  569. //assumingfollowingstructure
  570. //div->inputtype='file'
  571. removeNode(this._input.parentNode);
  572. removeClass(self._button,self._settings.hoverClass);
  573. form.appendChild(this._input);
  574. form.submit();
  575. //requestset,cleanup
  576. removeNode(form);
  577. form=null;
  578. removeNode(this._input);
  579. this._input=null;
  580. //GetresponsefromiframeandfireonCompleteeventwhenready
  581. this._getResponse(iframe,file);
  582. //getreadyfornextrequest
  583. this._createInput();
  584. }
  585. };
  586. })();
原文链接:https://www.f2er.com/ajax/162685.html

猜你在找的Ajax相关文章