1、创建页面并编写HTML
- 上传文档:
- <divclass="uploadFile">
- <spanid="doc"><inputtype="text"disabled="disabled"/></span>
- <inputtype="hidden"id="hidFileName"/>
- <inputtype="button"id="btnUploadFile"value="上传"/>
- <inputtype="button"id="btnDeleteFile"value="删除"/>
- </div>
- 上传图片:
- <divclass="uploadImg">
- <imgid="imgShow"src="/images/nophoto.gif"/>
- <inputtype="hidden"id="hidImgName"/>
- <inputtype="button"id="btnUploadImg"value="上传"/>
- <inputtype="button"id="btnDeleteImg"value="删除"/>
- </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文件
- <scriptsrc="/js/common/AjaxUpload.js"type="text/javascript"></script>
<script src="/js/common/AjaxUpload.js" type="text/javascript"></script>3、编写JS脚本
- window.onload=function(){
- init();//初始化
- }
- //初始化
- functioninit(){
- //初始化文档上传
- varbtnFile=document.getElementById("btnUploadFile");
- vardoc=document.getElementById("doc");
- varhidFileName=document.getElementById("hidFileName");
- document.getElementById("btnDeleteFile").onclick=function(){DelFile(doc,hidFileName);};
- g_AjxUploadFile(btnFile,doc,hidFileName);
- //初始化图片上传
- varbtnImg=document.getElementById("btnUploadImg");
- varimg=document.getElementById("imgShow");
- varhidImgName=document.getElementById("hidImgName");
- document.getElementById("btnDeleteImg").onclick=function(){DelImg(img,hidImgName);};
- g_AjxUploadImg(btnImg,img,hidImgName);
- }
- varg_AjxTempDir="/file/temp/";
- //文档上传
- functiong_AjxUploadFile(btn,hidPut,action){
- varbutton=btn,interval;
- newAjaxUpload(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("您上传的文档格式不对,请重新选择!");
- returnfalse;
- }
- },
- onComplete:function(file,response){
- flagValue=response;
- if(flagValue=="1"){
- alert("您上传的文档格式不对,请重新选择!");
- }
- elseif(flagValue=="2"){
- alert("您上传的文档大于2M,请重新选择!");
- }
- elseif(flagValue=="3"){
- alert("文档上传失败!");
- }
- else{
- hidPut.value=response;
- doc.innerHTML="<ahref='"+g_AjxTempDir+response+"'target='_blank'>"+response+"</a>";
- }
- }
- });
- }
- //图片上传
- functiong_AjxUploadImg(btn,hidPut){
- varbutton=btn,{
- action:'/Common/UploadHandler.ashx?fileType=img',ext){
- if(!(ext&&/^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))){
- alert("您上传的图片格式不对,请重新选择!");
- returnfalse;
- }
- },response){
- flagValue=response;
- if(flagValue=="1"){
- alert("您上传的图片格式不对,请重新选择!");
- }
- elseif(flagValue=="2"){
- alert("您上传的图片大于200K,请重新选择!");
- }
- elseif(flagValue=="3"){
- alert("图片上传失败!");
- }
- else{
- hidPut.value=response;
- img.src=g_AjxTempDir+response;
- }
- }
- });
- }
- //删除文档
- functionDelFile(doc,hidPut){
- hidPut.value="";
- doc.innerHTML="<inputtype=\"text\"disabled=\"disabled\"/>";
- }
- //删除图片
- functionDelImg(img,hidPut){
- hidPut.value="";
- img.src="/images/nophoto.gif";
- }
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处理程序
- <%@WebHandlerLanguage="C#"Class="UploadHandler"%>
- usingSystem;
- usingSystem.Web;
- usingSystem.Text.RegularExpressions;
- usingSystem.IO;
- publicclassUploadHandler:IHttpHandler{
- privatestring_filedir="";//文件目录
- ///<summary>
- ///处理上传文件(1:文件格式不正确、2:文件大小不正确、3:上传失败、文件名称:上传成功)
- ///</summary>
- ///<paramname="context"></param>
- publicvoidProcessRequest(HttpContextcontext){
- _filedir=context.Server.MapPath(@"/file/temp/");
- try
- {
- stringresult="3";
- stringfileType=context.Request.QueryString["fileType"];//获取上传文件类型
- if(fileType=="file")
- {
- result=UploadFile(context);//文档上传
- }
- elseif(fileType=="img")
- {
- result=UploadImg(context);//图片上传
- }
- context.Response.Write(result);
- }
- catch
- {
- context.Response.Write("3");//3文件上传失败
- }
- }
- ///<summary>
- ///文档上传
- ///</summary>
- ///<paramname="context"></param>
- ///<returns></returns>
- privatestringUploadFile(HttpContextcontext)
- {
- intcout=context.Request.Files.Count;
- if(cout>0)
- {
- HttpPostedFilehpf=context.Request.Files[0];
- if(hpf!=null)
- {
- stringfileExt=Path.GetExtension(hpf.FileName).ToLower();
- //只能上传文件,过滤不可上传的文件类型
- stringfileFilt=".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......";
- if(fileFilt.IndexOf(fileExt)<=-1)
- {
- return"1";
- }
- //判断文件大小
- intlength=hpf.ContentLength;
- if(length>2097152)
- {
- return"2";
- }
- Randomrd=newRandom();
- DateTimenowTime=DateTime.Now;
- 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);
- if(!Directory.Exists(_filedir))
- {
- Directory.CreateDirectory(_filedir);
- }
- stringfileName=_filedir+newFileName;
- hpf.SaveAs(fileName);
- returnnewFileName;
- }
- }
- return"3";
- }
- ///<summary>
- ///图片上传
- ///</summary>
- ///<paramname="context"></param>
- ///<returns></returns>
- privatestringUploadImg(HttpContextcontext)
- {
- intcout=context.Request.Files.Count;
- if(cout>0)
- {
- HttpPostedFilehpf=context.Request.Files[0];
- if(hpf!=null)
- {
- stringfileExt=Path.GetExtension(hpf.FileName).ToLower();
- //只能上传文件,过滤不可上传的文件类型
- stringfileFilt=".gif|.jpg|.PHP|.jsp|.jpeg|.png|......";
- if(fileFilt.IndexOf(fileExt)<=-1)
- {
- return"1";
- }
- //判断文件大小
- intlength=hpf.ContentLength;
- if(length>204800)
- {
- return"2";
- }
- Randomrd=newRandom();
- DateTimenowTime=DateTime.Now;
- 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);
- if(!Directory.Exists(_filedir))
- {
- Directory.CreateDirectory(_filedir);
- }
- stringfileName=_filedir+newFileName;
- hpf.SaveAs(fileName);
- returnnewFileName;
- }
- }
- return"3";
- }
- #regionIHttpHandler成员
- publicboolIsReusable
- {
- get{thrownewNotImplementedException();}
- }
- #endregion
- }
<%@ 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样式
/*上传文件*/ .uploadFile{margin-bottom:10px;} /*上传图片*/ .uploadImg{} .uploadImg img{width:102px; height:64px; border:1px solid #CCCCCC; display: block;}附件2:AjaxUpload.js文件
- /**
- *AJAXUpload(http://valums.com/ajax-upload/)
- *Copyright(c)AndrisValums
- *LicensedundertheMITlicense(http://valums.com/mit-license/)
- *ThankstoGaryHaran,DavidMark,CoreyBurnsandothersforcontributions
- */
- (function(){
- /*globalwindow*/
- /*jslintbrowser:true,devel:true,undef:true,nomen:true,bitwise:true,regexp:true,newcap:true,immed:true*/
- /**
- *WrapperforFireBug'sconsole.log
- */
- functionlog(){
- if(typeof(console)!='undefined'&&typeof(console.log)=='function'){
- Array.prototype.unshift.call(arguments,'[AjaxUpload]');
- console.log(Array.prototype.join.call(arguments,''));
- }
- }
- /**
- *Attacheseventtoadomelement.
- *@param{Element}el
- *@paramtypeeventname
- *@paramfncallbackThisreferstothepassedelement
- */
- functionaddEvent(el,type,fn){
- if(el.addEventListener){
- el.addEventListener(type,fn,false);
- }elseif(el.attachEvent){
- el.attachEvent('on'+type,function(){
- fn.call(el);
- });
- }else{
- thrownewError('notsupportedorDOMnotloaded');
- }
- }
- /**
- *Attachesresizeeventtoawindow,limiting
- *numberofeventfired.Firesonlywhenencounteres
- *delayof100afterseriesofevents.
- *
- *Somebrowsersfireeventmultipletimeswhenresizing
- *http://www.quirksmode.org/dom/events/resize.html
- *
- *@paramfncallbackThisreferstothepassedelement
- */
- functionaddResizeEvent(fn){
- vartimeout;
- addEvent(window,'resize',function(){
- if(timeout){
- clearTimeout(timeout);
- }
- timeout=setTimeout(fn,100);
- });
- }
- //Needsmoretesting,willberewritenfornextversion
- //getOffsetfunctioncopiedfromjQuerylib(http://jquery.com/)
- if(document.documentElement.getBoundingClientRect){
- //GetOffsetusinggetBoundingClientRect
- //http://ejohn.org/blog/getboundingclientrect-is-awesome/
- vargetOffset=function(el){
- varBox=el.getBoundingClientRect();
- vardoc=el.ownerDocument;
- varbody=doc.body;
- vardocElem=doc.documentElement;//forie
- varclientTop=docElem.clientTop||body.clientTop||0;
- varclientLeft=docElem.clientLeft||body.clientLeft||0;
- //InInternetExplorer7getBoundingClientRectpropertyistreatedasphysical,
- //whileothersarelogical.Makealllogical,likeinIE8.
- varzoom=1;
- if(body.getBoundingClientRect){
- varbound=body.getBoundingClientRect();
- zoom=(bound.right-bound.left)/body.clientWidth;
- }
- if(zoom>1){
- clientTop=0;
- clientLeft=0;
- }
- vartop=Box.top/zoom+(window.pageYOffset||docElem&&docElem.scrollTop/zoom||body.scrollTop/zoom)-clientTop,
- left=Box.left/zoom+(window.pageXOffset||docElem&&docElem.scrollLeft/zoom||body.scrollLeft/zoom)-clientLeft;
- return{
- top:top,
- left:left
- };
- };
- }else{
- //Getoffsetaddingalloffsets
- vargetOffset=function(el){
- vartop=0,
- left=0;
- do{
- top+=el.offsetTop||0;
- left+=el.offsetLeft||0;
- el=el.offsetParent;
- }while(el);
- return{
- left:left,
- top:top
- };
- };
- }
- /**
- *Returnsleft,top,rightandbottompropertiesdescribingtheborder-Box,
- *inpixels,withthetop-leftrelativetothebody
- *@param{Element}el
- *@return{Object}Containsleft,right,bottom
- */
- functiongetBox(el){
- varleft,bottom;
- varoffset=getOffset(el);
- left=offset.left;
- top=offset.top;
- right=left+el.offsetWidth;
- bottom=top+el.offsetHeight;
- return{
- left:left,
- right:right,
- top:top,
- bottom:bottom
- };
- }
- /**
- *Helperthattakesobjectliteral
- *andaddallpropertiestoelement.style
- *@param{Element}el
- *@param{Object}styles
- */
- functionaddStyles(el,styles){
- for(varnameinstyles){
- if(styles.hasOwnProperty(name)){
- el.style[name]=styles[name];
- }
- }
- }
- /**
- *Functionplacesanabsolutelypositioned
- *elementontopofthespecifiedelement
- *copyingpositionanddimentions.
- *@param{Element}from
- *@param{Element}to
- */
- functioncopyLayout(from,to){
- varBox=getBox(from);
- addStyles(to,{
- position:'absolute',
- left:Box.left+'px',
- top:Box.top+'px',
- width:from.offsetWidth+'px',
- height:from.offsetHeight+'px'
- });
- }
- /**
- *Createsandreturnselementfromhtmlchunk
- *UsesinnerHTMLtocreateanelement
- */
- vartoElement=(function(){
- vardiv=document.createElement('div');
- returnfunction(html){
- div.innerHTML=html;
- varel=div.firstChild;
- returndiv.removeChild(el);
- };
- })();
- /**
- *Functiongeneratesuniqueid
- *@returnuniqueid
- */
- vargetUID=(function(){
- varid=0;
- returnfunction(){
- return'ValumsAjaxUpload'+id++;
- };
- })();
- /**
- *Getfilenamefrompath
- *@param{String}filepathtofile
- *@returnfilename
- */
- functionfileFromPath(file){
- returnfile.replace(/.*(\/|\\)/,"");
- }
- /**
- *Getfileextensionlowercase
- *@param{String}filename
- *@returnfileextenstion
- */
- functiongetExt(file){
- return(-1!==file.indexOf('.'))?file.replace(/.*[.]/,''):'';
- }
- functionhasClass(el,name){
- varre=newRegExp('\\b'+name+'\\b');
- returnre.test(el.className);
- }
- functionaddClass(el,name){
- if(!hasClass(el,name)){
- el.className+=''+name;
- }
- }
- functionremoveClass(el,name){
- varre=newRegExp('\\b'+name+'\\b');
- el.className=el.className.replace(re,'');
- }
- functionremoveNode(el){
- el.parentNode.removeChild(el);
- }
- /**
- *Easystylinganduploading
- *@constructor
- *@parambuttonAnelementyouwantconvertto
- *uploadbutton.Testeddimentionsupto500x500px
- *@param{Object}optionsSeedefaultsbelow.
- */
- window.AjaxUpload=function(button,options){
- this._settings={
- //Locationoftheserver-sideuploadscript
- action:'upload.PHP',
- //Fileuploadname
- name:'userfile',
- //Additionaldatatosend
- data:{},
- //Submitfileassoonasit'sselected
- autoSubmit:true,
- //Thetypeofdatathatyou'reexpectingbackfromtheserver.
- //htmlandxmlaredetectedautomatically.
- //Onlyusefulwhenyouareusingjsondataasaresponse.
- //Setto"json"inthatcase.
- responseType:false,
- //Classappliedtobuttonwhenmouseishovered
- hoverClass:'hover',
- //ClassappliedtobuttonwhenAUisdisabled
- disabledClass:'disabled',
- //Whenuserselectsafile,usefulwithautoSubmitdisabled
- //Youcanreturnfalsetocancelupload
- onChange:function(file,extension){},
- //Callbacktofirebeforefileisuploaded
- //Youcanreturnfalsetocancelupload
- onSubmit:function(file,
- //Firedwhenfileuploadiscompleted
- //WARNING!DONOTUSE"FALSE"STRINGASARESPONSE!
- onComplete:function(file,response){}
- };
- //Mergetheusersoptionswithourdefaults
- for(variinoptions){
- if(options.hasOwnProperty(i)){
- this._settings[i]=options[i];
- }
- }
- //buttonisn'tnecessaryadomelement
- if(button.jquery){
- //jQueryobjectwaspassed
- button=button[0];
- }elseif(typeofbutton=="string"){
- if(/^#.*/.test(button)){
- //IfjQueryuserpasses#elementIddon'tbreakit
- button=button.slice(1);
- }
- button=document.getElementById(button);
- }
- if(!button||button.nodeType!==1){
- thrownewError("Pleasemakesurethatyou'repassingavalidelement");
- }
- if(button.nodeName.toUpperCase()=='A'){
- //disablelink
- addEvent(button,'click',function(e){
- if(e&&e.preventDefault){
- e.preventDefault();
- }elseif(window.event){
- window.event.returnValue=false;
- }
- });
- }
- //DOMelement
- this._button=button;
- //DOMelement
- this._input=null;
- //Ifdisabledclickingonbuttonwon'tdoanything
- this._disabled=false;
- //ifthebuttonwasdisabledbeforerefreshifwillremain
- //disabledinFireFox,let'sfixit
- this.enable();
- this._rerouteClicks();
- };
- //assigningmethodstoourclass
- AjaxUpload.prototype={
- setData:function(data){
- this._settings.data=data;
- },
- disable:function(){
- addClass(this._button,this._settings.disabledClass);
- this._disabled=true;
- varnodeName=this._button.nodeName.toUpperCase();
- if(nodeName=='INPUT'||nodeName=='BUTTON'){
- this._button.setAttribute('disabled','disabled');
- }
- //hideinput
- if(this._input){
- //WeusevisibilityinsteadofdisplaytofixproblemwithSafari4
- //Theproblemisthatthevalueofinputdoesn'tchangeifit
- //hasdisplaynonewhenuserselectsafile
- this._input.parentNode.style.visibility='hidden';
- }
- },
- enable:function(){
- removeClass(this._button,this._settings.disabledClass);
- this._button.removeAttribute('disabled');
- this._disabled=false;
- },
- /**
- *Createsinvisiblefileinput
- *thatwillhoverabovethebutton
- *<div><inputtype='file'/></div>
- */
- _createInput:function(){
- varself=this;
- varinput=document.createElement("input");
- input.setAttribute('type','file');
- input.setAttribute('name',this._settings.name);
- addStyles(input,{
- 'position':'absolute',
- //inOperaonly'browse'button
- //isclickableanditislocatedat
- //therightsideoftheinput
- 'right':0,
- 'margin':0,
- 'padding':0,
- 'fontSize':'480px',
- 'cursor':'pointer'
- });
- vardiv=document.createElement("div");
- addStyles(div,{
- 'display':'block',
- 'position':'absolute',
- 'overflow':'hidden',
- 'opacity':0,
- //Makesurebrowsebuttonisintherightside
- //inInternetExplorer
- 'direction':'ltr',
- //MaxzIndexsupportedbyOpera9.0-9.2
- 'zIndex':2147483583
- });
- //Makesurethatelementopacityexists.
- //OtherwiseuseIEfilter
- if(div.style.opacity!=="0"){
- if(typeof(div.filters)=='undefined'){
- thrownewError('Opacitynotsupportedbythebrowser');
- }
- div.style.filter="alpha(opacity=0)";
- }
- addEvent(input,'change',function(){
- if(!input||input.value===''){
- return;
- }
- //Getfilenamefrominput,required
- //assomebrowsershavepathinsteadofit
- varfile=fileFromPath(input.value);
- if(false===self._settings.onChange.call(self,file,getExt(file))){
- self._clearInput();
- return;
- }
- //Submitformwhenvalueischanged
- if(self._settings.autoSubmit){
- self.submit();
- }
- });
- addEvent(input,'mouSEOver',function(){
- addClass(self._button,self._settings.hoverClass);
- });
- addEvent(input,'mouSEOut',function(){
- removeClass(self._button,self._settings.hoverClass);
- //WeusevisibilityinsteadofdisplaytofixproblemwithSafari4
- //Theproblemisthatthevalueofinputdoesn'tchangeifit
- //hasdisplaynonewhenuserselectsafile
- input.parentNode.style.visibility='hidden';
- });
- div.appendChild(input);
- document.body.appendChild(div);
- this._input=input;
- },
- _clearInput:function(){
- if(!this._input){
- return;
- }
- //this._input.value='';Doesn'tworkinIE6
- removeNode(this._input.parentNode);
- this._input=null;
- this._createInput();
- removeClass(this._button,this._settings.hoverClass);
- },
- /**
- *Functionmakessurethatwhenuserclicksuploadbutton,
- *thethis._inputisclickedinstead
- */
- _rerouteClicks:function(){
- varself=this;
- //IEwilllaterdisplay'accessdenied'error
- //ifyouuseusingself._input.click()
- //otherbrowsersjustignoreclick()
- addEvent(self._button,function(){
- if(self._disabled){
- return;
- }
- if(!self._input){
- self._createInput();
- }
- vardiv=self._input.parentNode;
- copyLayout(self._button,div);
- div.style.visibility='visible';
- });
- //commentedbecausewenowhideinputonmouseleave
- /**
- *Whenthewindowisresizedtheelements
- *canbemisalignedifbuttonpositiondepends
- *onwindowsize
- */
- //addResizeEvent(function(){
- //if(self._input){
- //copyLayout(self._button,self._input.parentNode);
- //}
- //});
- },
- /**
- *Createsiframewithuniquename
- *@return{Element}iframe
- */
- _createIframe:function(){
- //Wecan'tusegetTime,becauseitsometimesreturn
- //samevalueinsafari:(
- varid=getUID();
- //Wecan'tusefollowingcodeasthenameattribute
- //won'tbeproperlyregisteredinIE6,andnewwindow
- //onformsubmitwillopen
- //variframe=document.createElement('iframe');
- //iframe.setAttribute('name',id);
- variframe=toElement('<iframesrc="javascript:false;"name="'+id+'"/>');
- //src="javascript:false;wasadded
- //becauseitpossiblyremovesie6prompt
- //"Thispagecontainsbothsecureandnonsecureitems"
- //Anyway,itdoesn'tdoanyharm.
- iframe.setAttribute('id',id);
- iframe.style.display='none';
- document.body.appendChild(iframe);
- returniframe;
- },
- /**
- *Createsform,thatwillbesubmittedtoiframe
- *@param{Element}iframeWheretosubmit
- *@return{Element}form
- */
- _createForm:function(iframe){
- varsettings=this._settings;
- //Wecan'tusethefollowingcodeinIE6
- //varform=document.createElement('form');
- //form.setAttribute('method','post');
- //form.setAttribute('enctype','multipart/form-data');
- //Becauseinthiscasefilewon'tbeattachedtorequest
- varform=toElement('<formmethod="post"enctype="multipart/form-data"></form>');
- form.setAttribute('action',settings.action);
- form.setAttribute('target',iframe.name);
- form.style.display='none';
- document.body.appendChild(form);
- //Createhiddeninputelementforeachdatakey
- for(varpropinsettings.data){
- if(settings.data.hasOwnProperty(prop)){
- varel=document.createElement("input");
- el.setAttribute('type','hidden');
- el.setAttribute('name',prop);
- el.setAttribute('value',settings.data[prop]);
- form.appendChild(el);
- }
- }
- returnform;
- },
- /**
- *GetsresponsefromiframeandfiresonCompleteeventwhenready
- *@paramiframe
- *@paramfileFilenametouseinonCompletecallback
- */
- _getResponse:function(iframe,file){
- //gettingresponse
- vartoDeleteFlag=false,
- self=this,
- settings=this._settings;
- addEvent(iframe,'load',function(){
- if(//ForSafari
- iframe.src=="javascript:'%3Chtml%3E%3C/html%3E';"||
- //ForFF,IE
- iframe.src=="javascript:'<html></html>';"){
- //Firsttimearound,donotdelete.
- //Wereloadtoblankpage,sothatreloadingmainpage
- //doesnotre-submitthepost.
- if(toDeleteFlag){
- //FixbusystateinFF3
- setTimeout(function(){
- removeNode(iframe);
- },
- 0);
- }
- return;
- }
- vardoc=iframe.contentDocument?iframe.contentDocument:window.frames[iframe.id].document;
- //fixingOpera9.26,10.00
- if(doc.readyState&&doc.readyState!='complete'){
- //Operafiresloadeventmultipletimes
- //EvenwhentheDOMisnotreadyyet
- //thisfixshouldnotaffectotherbrowsers
- return;
- }
- //fixingOpera9.64
- if(doc.body&&doc.body.innerHTML=="false"){
- //InOpera9.64eventwasfiredsecondtime
- //whenbody.innerHTMLchangedfromfalse
- //toserverresponseapprox.after1sec
- return;
- }
- varresponse;
- if(doc.XMLDocument){
- //responseisaxmldocumentInternetExplorerproperty
- response=doc.XMLDocument;
- }elseif(doc.body){
- //responseishtmldocumentorplaintext
- response=doc.body.innerHTML;
- if(settings.responseType&&settings.responseType.toLowerCase()=='json'){
- //Ifthedocumentwassentas'application/javascript'or
- //'text/javascript',thenthebrowserwrapsthetextina<pre>
- //tagandperformshtmlencodingonthecontents.Inthiscase,
- //weneedtopulltheoriginaltextcontentfromthetextnode's
- //nodeValuepropertytoretrievetheunmangledcontent.
- //NotethatIE6onlyunderstandstext/html
- if(doc.body.firstChild&&doc.body.firstChild.nodeName.toUpperCase()=='PRE'){
- response=doc.body.firstChild.firstChild.nodeValue;
- }
- if(response){
- response=eval("("+response+")");
- }else{
- response={};
- }
- }
- }else{
- //responseisaxmldocument
- response=doc;
- }
- settings.onComplete.call(self,response);
- //Reloadblankpage,sothatreloadingmainpage
- //doesnotre-submitthepost.Also,rememberto
- //deletetheframe
- toDeleteFlag=true;
- //FixIEmixedcontentissue
- iframe.src="javascript:'<html></html>';";
- });
- },
- /**
- *Uploadfilecontainedinthis._input
- */
- submit:function(){
- varself=this,
- settings=this._settings;
- if(!this._input||this._input.value===''){
- return;
- }
- varfile=fileFromPath(this._input.value);
- //userreturnedfalsetocancelupload
- if(false===settings.onSubmit.call(this,getExt(file))){
- this._clearInput();
- return;
- }
- //sendingrequest
- variframe=this._createIframe();
- varform=this._createForm(iframe);
- //assumingfollowingstructure
- //div->inputtype='file'
- removeNode(this._input.parentNode);
- removeClass(self._button,self._settings.hoverClass);
- form.appendChild(this._input);
- form.submit();
- //requestset,cleanup
- removeNode(form);
- form=null;
- removeNode(this._input);
- this._input=null;
- //GetresponsefromiframeandfireonCompleteeventwhenready
- this._getResponse(iframe,file);
- //getreadyfornextrequest
- this._createInput();
- }
- };
- })();