AjaxUpload.js实现文件的一键上传

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

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

图1 文件上传

图2 文件上传

1、创建页面并编写HTML

  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>
上传文档:
<div class="uploadFile">
    <span id="doc"><input type="text" disabled="disabled" /></span>
    <input type="hidden" id="hidFileName"  />
    <input type="button" id="btnUploadFile" value="上传" />
    <input type="button" id="btnDeleteFile" value="删除"  />
</div>

上传图片:
<div class="uploadImg">
    <img id="imgShow" src="/images/nophoto.gif" />
    <input type="hidden" id="hidImgName" />
    <input type="button" id="btnUploadImg" value="上传" />
    <input type="button" id="btnDeleteImg" value="删除" />
</div>
2、引用AjaxUpload.js文件
  1. <scriptsrc="/js/common/AjaxUpload.js"type="text/javascript"></script>
<script src="/js/common/AjaxUpload.js" type="text/javascript"></script>
3、编写JS脚本
  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',ext){
  55. if(!(ext&&/^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))){
  56. alert("您上传图片格式不对,请重新选择!");
  57. returnfalse;
  58. }
  59. },response){
  60. flagValue=response;
  61. if(flagValue=="1"){
  62. alert("您上传图片格式不对,请重新选择!");
  63. }
  64. elseif(flagValue=="2"){
  65. alert("您上传图片大于200K,请重新选择!");
  66. }
  67. elseif(flagValue=="3"){
  68. alert("图片上传失败!");
  69. }
  70. else{
  71. hidPut.value=response;
  72. img.src=g_AjxTempDir+response;
  73. }
  74. }
  75. });
  76. }
  77. //删除文档
  78. functionDelFile(doc,hidPut){
  79. hidPut.value="";
  80. doc.innerHTML="<inputtype=\"text\"disabled=\"disabled\"/>";
  81. }
  82. //删除图片
  83. functionDelImg(img,hidPut){
  84. hidPut.value="";
  85. img.src="/images/nophoto.gif";
  86. }
window.onload = function() {
    init();  //初始化
}

//初始化
function init() {
    //初始化文档上传
    var btnFile = document.getElementById("btnUploadFile");
    var doc = document.getElementById("doc");
    var hidFileName = document.getElementById("hidFileName");
    document.getElementById("btnDeleteFile").onclick = function() { DelFile(doc,hidFileName); };
    g_AjxUploadFile(btnFile,hidFileName);
    
    //初始化图片上传
    var btnImg = document.getElementById("btnUploadImg");
    var img = document.getElementById("imgShow");
    var hidImgName = document.getElementById("hidImgName");
    document.getElementById("btnDeleteImg").onclick = function() { DelImg(img,hidImgName); };
    g_AjxUploadImg(btnImg,hidImgName);
}


var g_AjxTempDir = "/file/temp/";
//文档上传
function g_AjxUploadFile(btn,action) {
    var button = btn,interval;
    new AjaxUpload(button,{
    action: ((action == null || action == undefined) ? '/Common/UploadHandler.ashx?fileType=file' : action),data: {},name: 'myfile',onSubmit: function(file,ext) {
            if (!(ext && /^(rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|RAR|ZIP|PDF|PDFX|TXT|CSV|XLS|XLSX|DOC|DOCX)$/.test(ext))) {
                alert("您上传的文档格式不对,请重新选择!");
                return false;
            }
        },onComplete: function(file,response) {
            flagValue = response;
            if (flagValue == "1") {
                alert("您上传的文档格式不对,请重新选择!");
            }
            else if (flagValue == "2") {
                alert("您上传的文档大于2M,请重新选择!");
            }
            else if (flagValue == "3") {
                alert("文档上传失败!");
            }
            else {
                hidPut.value = response;
                doc.innerHTML="<a href='" + g_AjxTempDir + response + "' target='_blank'>" + response + "</a>";
            }
        }
    });
}
//图片上传
function g_AjxUploadImg(btn,hidPut) {
    var button = btn,{
        action: '/Common/UploadHandler.ashx?fileType=img',ext) {
            if (!(ext && /^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))) {
                alert("您上传图片格式不对,请重新选择!");
                return false;
            }
        },response) {
            flagValue = response;
            if (flagValue == "1") {
                alert("您上传图片格式不对,请重新选择!");
            }
            else if (flagValue == "2") {
                alert("您上传图片大于200K,请重新选择!");
            }
            else if (flagValue == "3") {
                alert("图片上传失败!");
            }
            else {
                hidPut.value = response;
                img.src = g_AjxTempDir + response;
            }
        }
    });
}

//删除文档
function DelFile(doc,hidPut) {
    hidPut.value = "";
    doc.innerHTML = "<input type=\"text\" disabled=\"disabled\" />";
}

//删除图片
function DelImg(img,hidPut) {
    hidPut.value = "";
    img.src = "/images/nophoto.gif";
}

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

[csharp] view plain copy print ?
  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. }
<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;

public class UploadHandler : IHttpHandler {
    private string _filedir = "";    //文件目录
    /// <summary>
    /// 处理上传文件(1:文件格式不正确、2:文件大小不正确、3:上传失败、文件名称:上传成功)
    /// </summary>
    /// <param name="context"></param>
    public void ProcessRequest (HttpContext context) {
        _filedir = context.Server.MapPath(@"/file/temp/");
        try
        {
            string result = "3";
            string fileType = context.Request.QueryString["fileType"]; //获取上传文件类型
            if (fileType == "file")
            {
                result = UploadFile(context);  //文档上传
            }
            else if (fileType == "img")
            {
                result = UploadImg(context);   //图片上传
            }
            context.Response.Write(result);
        }
        catch
        {
            context.Response.Write("3");//3文件上传失败
        }
    }
    
    /// <summary>
    /// 文档上传
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string UploadFile(HttpContext context)
    {
        int cout = context.Request.Files.Count;
        if (cout > 0)
        {
            HttpPostedFile hpf = context.Request.Files[0];
            if (hpf != null)
            {
                string fileExt = Path.GetExtension(hpf.FileName).ToLower();
                //只能上传文件,过滤不可上传文件类型  
                string fileFilt = ".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......";
                if (fileFilt.IndexOf(fileExt) <= -1)
                {
                    return "1";
                }
                
                //判断文件大小  
                int length = hpf.ContentLength;
                if (length > 2097152)
                {
                    return "2";
                }  
               
                Random rd = new Random();
                DateTime nowTime = DateTime.Now;
                string newFileName = 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);
                if (!Directory.Exists(_filedir))
                {
                    Directory.CreateDirectory(_filedir);
                }
                string fileName = _filedir + newFileName;
                hpf.SaveAs(fileName);
                return newFileName;
            }

        }
        return "3";
    }

    /// <summary>
    /// 图片上传
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string UploadImg(HttpContext context)
    {
        int cout = context.Request.Files.Count;
        if (cout > 0)
        {
            HttpPostedFile hpf = context.Request.Files[0];
            if (hpf != null)
            {
                string fileExt = Path.GetExtension(hpf.FileName).ToLower();
                //只能上传文件,过滤不可上传文件类型  
                string fileFilt = ".gif|.jpg|.PHP|.jsp|.jpeg|.png|......";
                if (fileFilt.IndexOf(fileExt) <= -1)
                {
                    return "1";
                }
                
                //判断文件大小  
                int length = hpf.ContentLength;
                if (length > 204800)
                {
                    return "2";
                }
                
                Random rd = new Random();
                DateTime nowTime = DateTime.Now;
                string newFileName = 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);
                if (!Directory.Exists(_filedir))
                {
                    Directory.CreateDirectory(_filedir);
                }
                string fileName = _filedir + newFileName;
                hpf.SaveAs(fileName);
                return newFileName;
            }

        }
        return "3";
    }
    
    #region IHttpHandler 成员

    public bool IsReusable
    {
        get { throw new NotImplementedException(); }
    }

    #endregion
}
附件1:页面CSS样式
  1. /*上传文件*/
  2. .uploadFile{margin-bottom:10px;}
  3. /*上传图片*/
  4. .uploadImg{}
  5. .uploadImgimg{width:102px;height:64px;border:1pxsolid#CCCCCC;display:block;}
/*上传文件*/
.uploadFile{margin-bottom:10px;}
/*上传图片*/
.uploadImg{}
.uploadImg img{width:102px; height:64px; border:1px solid #CCCCCC; display: block;}
附件2:AjaxUpload.js文件
[javascript] view plain copy print ?
  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. 'opacity':0,
  334. //Makesurebrowsebuttonisintherightside
  335. //inInternetExplorer
  336. 'direction':'ltr',
  337. //MaxzIndexsupportedbyOpera9.0-9.2
  338. 'zIndex':2147483583
  339. });
  340. //Makesurethatelementopacityexists.
  341. //OtherwiseuseIEfilter
  342. if(div.style.opacity!=="0"){
  343. if(typeof(div.filters)=='undefined'){
  344. thrownewError('Opacitynotsupportedbythebrowser');
  345. }
  346. div.style.filter="alpha(opacity=0)";
  347. }
  348. addEvent(input,'change',function(){
  349. if(!input||input.value===''){
  350. return;
  351. }
  352. //Getfilenamefrominput,required
  353. //assomebrowsershavepathinsteadofit
  354. varfile=fileFromPath(input.value);
  355. if(false===self._settings.onChange.call(self,file,getExt(file))){
  356. self._clearInput();
  357. return;
  358. }
  359. //Submitformwhenvalueischanged
  360. if(self._settings.autoSubmit){
  361. self.submit();
  362. }
  363. });
  364. addEvent(input,'mouSEOver',function(){
  365. addClass(self._button,self._settings.hoverClass);
  366. });
  367. addEvent(input,'mouSEOut',function(){
  368. removeClass(self._button,self._settings.hoverClass);
  369. //WeusevisibilityinsteadofdisplaytofixproblemwithSafari4
  370. //Theproblemisthatthevalueofinputdoesn'tchangeifit
  371. //hasdisplaynonewhenuserselectsafile
  372. input.parentNode.style.visibility='hidden';
  373. });
  374. div.appendChild(input);
  375. document.body.appendChild(div);
  376. this._input=input;
  377. },
  378. _clearInput:function(){
  379. if(!this._input){
  380. return;
  381. }
  382. //this._input.value='';Doesn'tworkinIE6
  383. removeNode(this._input.parentNode);
  384. this._input=null;
  385. this._createInput();
  386. removeClass(this._button,this._settings.hoverClass);
  387. },
  388. /**
  389. *Functionmakessurethatwhenuserclicksuploadbutton,
  390. *thethis._inputisclickedinstead
  391. */
  392. _rerouteClicks:function(){
  393. varself=this;
  394. //IEwilllaterdisplay'accessdenied'error
  395. //ifyouuseusingself._input.click()
  396. //otherbrowsersjustignoreclick()
  397. addEvent(self._button,function(){
  398. if(self._disabled){
  399. return;
  400. }
  401. if(!self._input){
  402. self._createInput();
  403. }
  404. vardiv=self._input.parentNode;
  405. copyLayout(self._button,div);
  406. div.style.visibility='visible';
  407. });
  408. //commentedbecausewenowhideinputonmouseleave
  409. /**
  410. *Whenthewindowisresizedtheelements
  411. *canbemisalignedifbuttonpositiondepends
  412. *onwindowsize
  413. */
  414. //addResizeEvent(function(){
  415. //if(self._input){
  416. //copyLayout(self._button,self._input.parentNode);
  417. //}
  418. //});
  419. },
  420. /**
  421. *Createsiframewithuniquename
  422. *@return{Element}iframe
  423. */
  424. _createIframe:function(){
  425. //Wecan'tusegetTime,becauseitsometimesreturn
  426. //samevalueinsafari:(
  427. varid=getUID();
  428. //Wecan'tusefollowingcodeasthenameattribute
  429. //won'tbeproperlyregisteredinIE6,andnewwindow
  430. //onformsubmitwillopen
  431. //variframe=document.createElement('iframe');
  432. //iframe.setAttribute('name',id);
  433. variframe=toElement('<iframesrc="javascript:false;"name="'+id+'"/>');
  434. //src="javascript:false;wasadded
  435. //becauseitpossiblyremovesie6prompt
  436. //"Thispagecontainsbothsecureandnonsecureitems"
  437. //Anyway,itdoesn'tdoanyharm.
  438. iframe.setAttribute('id',id);
  439. iframe.style.display='none';
  440. document.body.appendChild(iframe);
  441. returniframe;
  442. },
  443. /**
  444. *Createsform,thatwillbesubmittedtoiframe
  445. *@param{Element}iframeWheretosubmit
  446. *@return{Element}form
  447. */
  448. _createForm:function(iframe){
  449. varsettings=this._settings;
  450. //Wecan'tusethefollowingcodeinIE6
  451. //varform=document.createElement('form');
  452. //form.setAttribute('method','post');
  453. //form.setAttribute('enctype','multipart/form-data');
  454. //Becauseinthiscasefilewon'tbeattachedtorequest
  455. varform=toElement('<formmethod="post"enctype="multipart/form-data"></form>');
  456. form.setAttribute('action',settings.action);
  457. form.setAttribute('target',iframe.name);
  458. form.style.display='none';
  459. document.body.appendChild(form);
  460. //Createhiddeninputelementforeachdatakey
  461. for(varpropinsettings.data){
  462. if(settings.data.hasOwnProperty(prop)){
  463. varel=document.createElement("input");
  464. el.setAttribute('type','hidden');
  465. el.setAttribute('name',prop);
  466. el.setAttribute('value',settings.data[prop]);
  467. form.appendChild(el);
  468. }
  469. }
  470. returnform;
  471. },
  472. /**
  473. *GetsresponsefromiframeandfiresonCompleteeventwhenready
  474. *@paramiframe
  475. *@paramfileFilenametouseinonCompletecallback
  476. */
  477. _getResponse:function(iframe,file){
  478. //gettingresponse
  479. vartoDeleteFlag=false,
  480. self=this,
  481. settings=this._settings;
  482. addEvent(iframe,'load',function(){
  483. if(//ForSafari
  484. iframe.src=="javascript:'%3Chtml%3E%3C/html%3E';"||
  485. //ForFF,IE
  486. iframe.src=="javascript:'<html></html>';"){
  487. //Firsttimearound,donotdelete.
  488. //Wereloadtoblankpage,sothatreloadingmainpage
  489. //doesnotre-submitthepost.
  490. if(toDeleteFlag){
  491. //FixbusystateinFF3
  492. setTimeout(function(){
  493. removeNode(iframe);
  494. },
  495. 0);
  496. }
  497. return;
  498. }
  499. vardoc=iframe.contentDocument?iframe.contentDocument:window.frames[iframe.id].document;
  500. //fixingOpera9.26,10.00
  501. if(doc.readyState&&doc.readyState!='complete'){
  502. //Operafiresloadeventmultipletimes
  503. //EvenwhentheDOMisnotreadyyet
  504. //thisfixshouldnotaffectotherbrowsers
  505. return;
  506. }
  507. //fixingOpera9.64
  508. if(doc.body&&doc.body.innerHTML=="false"){
  509. //InOpera9.64eventwasfiredsecondtime
  510. //whenbody.innerHTMLchangedfromfalse
  511. //toserverresponseapprox.after1sec
  512. return;
  513. }
  514. varresponse;
  515. if(doc.XMLDocument){
  516. //responseisaxmldocumentInternetExplorerproperty
  517. response=doc.XMLDocument;
  518. }elseif(doc.body){
  519. //responseishtmldocumentorplaintext
  520. response=doc.body.innerHTML;
  521. if(settings.responseType&&settings.responseType.toLowerCase()=='json'){
  522. //Ifthedocumentwassentas'application/javascript'or
  523. //'text/javascript',thenthebrowserwrapsthetextina<pre>
  524. //tagandperformshtmlencodingonthecontents.Inthiscase,
  525. //weneedtopulltheoriginaltextcontentfromthetextnode's
  526. //nodeValuepropertytoretrievetheunmangledcontent.
  527. //NotethatIE6onlyunderstandstext/html
  528. if(doc.body.firstChild&&doc.body.firstChild.nodeName.toUpperCase()=='PRE'){
  529. response=doc.body.firstChild.firstChild.nodeValue;
  530. }
  531. if(response){
  532. response=eval("("+response+")");
  533. }else{
  534. response={};
  535. }
  536. }
  537. }else{
  538. //responseisaxmldocument
  539. response=doc;
  540. }
  541. settings.onComplete.call(self,response);
  542. //Reloadblankpage,sothatreloadingmainpage
  543. //doesnotre-submitthepost.Also,rememberto
  544. //deletetheframe
  545. toDeleteFlag=true;
  546. //FixIEmixedcontentissue
  547. iframe.src="javascript:'<html></html>';";
  548. });
  549. },
  550. /**
  551. *Uploadfilecontainedinthis._input
  552. */
  553. submit:function(){
  554. varself=this,
  555. settings=this._settings;
  556. if(!this._input||this._input.value===''){
  557. return;
  558. }
  559. varfile=fileFromPath(this._input.value);
  560. //userreturnedfalsetocancelupload
  561. if(false===settings.onSubmit.call(this,getExt(file))){
  562. this._clearInput();
  563. return;
  564. }
  565. //sendingrequest
  566. variframe=this._createIframe();
  567. varform=this._createForm(iframe);
  568. //assumingfollowingstructure
  569. //div->inputtype='file'
  570. removeNode(this._input.parentNode);
  571. removeClass(self._button,self._settings.hoverClass);
  572. form.appendChild(this._input);
  573. form.submit();
  574. //requestset,cleanup
  575. removeNode(form);
  576. form=null;
  577. removeNode(this._input);
  578. this._input=null;
  579. //GetresponsefromiframeandfireonCompleteeventwhenready
  580. this._getResponse(iframe,file);
  581. //getreadyfornextrequest
  582. this._createInput();
  583. }
  584. };
  585. })();
原文链接:https://www.f2er.com/ajax/164222.html

猜你在找的Ajax相关文章