一、

通过iframe来实现无刷新的的文件上传,其实是有刷新的,只是在iframe里面隐藏了而已

 

简单的原理说明:

<form id="form1" method="post" action="upload.do" enctype="multipart/form-data" target="uploadframe" >
<input type="file" id="upload" name="文件上传" />
</form>

<iframe id="uploadframe" name="result_frame" style="visibility:hidden;"></iframe>

 

form里面的target要与iframe里面的id的值相等,指示是form相应了post事件,也就是post时间相应的时候刷新的是iframe而不是整个页面。

 

二、

利用jQuery的插件AjaxFileUpload 可以简单地实现这个异步的上传的效果 插件地址: http://www.phpletter.com/Our-Projects/AjaxFileUpload/

 

<script type="text/javascript" language="javascript" src="js/jquery.js"></script>

<script type="text/javascript" language="javascript" src="js/ajaxfileupload.js"></script>

 

 
  
  1. 代码  
  2.  
  3.     function ajaxFileUpload()  
  4.     {  
  5.         $("#loading")  
  6.         .ajaxStart(function(){  
  7.             $(this).show();              
  8.         })  
  9.         .ajaxComplete(function(){  
  10.             $(this).hide();              
  11.         });  
  12.  
  13.         $.ajaxFileUpload  
  14.         (  
  15.             {  
  16.                 url:'Upload.ashx',  
  17.                 secureuri:false,  
  18.                 fileElementId:'fileToUpload',  
  19.                 dataType: 'json',  
  20.                 success: function (data, status)  
  21.                 {                  
  22.                     if(typeof(data.error) != 'undefined')  
  23.                     {  
  24.                         if(data.error != '')  
  25.                         {  
  26.                             alert(data.error);  
  27.                         }else  
  28.                         {  
  29.                             alert(data.msg);  
  30.                         }  
  31.                     }  
  32.                 },  
  33.                 error: function (data, status, e)  
  34.                 {  
  35.                     alert(e);  
  36.                 }  
  37.             }  
  38.         )  
  39.           
  40.         return false;  
  41.  
  42.     } 

<input id="fileToUpload" type="file" size="45" name="fileToUpload">

<input type="button" id="buttonUpload" ajaxFileUpload();">
上传</input>

 

 

Upload.ashx

 

 
  
  1. 代码  
  2.  
  3. if (Request.Files.Count > 0)  
  4.    {  
  5.     HttpPostedFile file = Request.Files[0];  
  6.     string msg = "";  
  7.     string error = "";  
  8.     if (file.ContentLength == 0)  
  9.      error = "文件长度为0";  
  10.     else  
  11.     {  
  12.      file.SaveAs(Server.MapPath("file") + "\\" + Path.GetFileName(file.FileName));  
  13.      msg = "上传成功";  
  14.     }  
  15.     string result = "{ error:'" + error + "', msg:'" + msg + "'}";  
  16.     Response.Write(result);  
  17.     Response.End();  
  18.    } 

PS:ajaxfileupload.js代码

 

 
  
  1. 代码  
  2.  
  3. jQuery.extend({  
  4.  
  5.     createUploadIframe: function(id, uri)  
  6.     {  
  7.             //create frame  
  8.             var frameId = 'jUploadFrame' + id;  
  9.               
  10.             if(window.ActiveXObject) {  
  11.                 var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');  
  12.                 if(typeof uri== 'boolean'){  
  13.                     io.src = 'javascript:false';  
  14.                 }  
  15.                 else if(typeof uri== 'string'){  
  16.                     io.src = uri;  
  17.                 }  
  18.             }  
  19.             else {  
  20.                 var io = document.createElement('iframe');  
  21.                 io.id = frameId;  
  22.                 io.name = frameId;  
  23.             }  
  24.             io.style.position = 'absolute';  
  25.             io.style.top = '-1000px';  
  26.             io.style.left = '-1000px';  
  27.  
  28.             document.body.appendChild(io);  
  29.  
  30.             return io              
  31.     },  
  32.     createUploadForm: function(id, fileElementId)  
  33.     {  
  34.         //create form      
  35.         var formId = 'jUploadForm' + id;  
  36.         var fileId = 'jUploadFile' + id;  
  37.         var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');      
  38.         var oldElement = $('#' + fileElementId);  
  39.         var newElement = $(oldElement).clone();  
  40.         $(oldElement).attr('id', fileId);  
  41.         $(oldElement).before(newElement);  
  42.         $(oldElement).appendTo(form);  
  43.         //set attributes  
  44.         $(form).css('position', 'absolute');  
  45.         $(form).css('top', '-1200px');  
  46.         $(form).css('left', '-1200px');  
  47.         $(form).appendTo('body');          
  48.         return form;  
  49.     },  
  50.  
  51.     ajaxFileUpload: function(s) {  
  52.         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout          
  53.         s = jQuery.extend({}, jQuery.ajaxSettings, s);  
  54.         var id = new Date().getTime()          
  55.         var form = jQuery.createUploadForm(id, s.fileElementId);  
  56.         var io = jQuery.createUploadIframe(id, s.secureuri);  
  57.         var frameId = 'jUploadFrame' + id;  
  58.         var formId = 'jUploadForm' + id;          
  59.         // Watch for a new set of requests  
  60.         if ( s.global && ! jQuery.active++ )  
  61.         {  
  62.             jQuery.event.trigger( "ajaxStart" );  
  63.         }              
  64.         var requestDone = false;  
  65.         // Create the request object  
  66.         var xml = {}     
  67.         if ( s.global )  
  68.             jQuery.event.trigger("ajaxSend", [xml, s]);  
  69.         // Wait for a response to come back  
  70.         var uploadCallback = function(isTimeout)  
  71.         {              
  72.             var io = document.getElementById(frameId);  
  73.             try   
  74.             {                  
  75.                 if(io.contentWindow)  
  76.                 {  
  77.                      xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;  
  78.                      xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;  
  79.                        
  80.                 }else if(io.contentDocument)  
  81.                 {  
  82.                      xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;  
  83.                     xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;  
  84.                 }                          
  85.             }catch(e)  
  86.             {  
  87.                 jQuery.handleError(s, xml, null, e);  
  88.             }  
  89.             if ( xml || isTimeout == "timeout")   
  90.             {                  
  91.                 requestDone = true;  
  92.                 var status;  
  93.                 try {  
  94.                     status = isTimeout != "timeout" ? "success" : "error";  
  95.                       
  96.                     // Make sure that the request was successful or notmodified  
  97.                     if ( status != "error" )  
  98.                     {  
  99.                         // process the data (runs the xml through httpData regardless of callback)  
  100.                         var data = jQuery.uploadHttpData( xml, s.dataType );      
  101.                         // If a local callback was specified, fire it and pass it the data  
  102.                         if ( s.success )  
  103.                             s.success( data, status );  
  104.       
  105.                         // Fire the global callback  
  106.                         if( s.global )  
  107.                             jQuery.event.trigger( "ajaxSuccess", [xml, s] );  
  108.                     } else  
  109.                         jQuery.handleError(s, xml, status);  
  110.                 } catch(e)   
  111.                 {  
  112.                     status = "error";  
  113.                     jQuery.handleError(s, xml, status, e);  
  114.                 }  
  115.  
  116.                 // The request was completed  
  117.                 if( s.global )  
  118.                     jQuery.event.trigger( "ajaxComplete", [xml, s] );  
  119.  
  120.                 // Handle the global AJAX counter  
  121.                 if ( s.global && ! --jQuery.active )  
  122.                     jQuery.event.trigger( "ajaxStop" );  
  123.  
  124.                 // Process result  
  125.                 if ( s.complete )  
  126.                     s.complete(xml, status);  
  127.  
  128.                 jQuery(io).unbind()  
  129.  
  130.                 setTimeout(function()  
  131.                                     {    try   
  132.                                         {  
  133.                                             $(io).remove();  
  134.                                             $(form).remove();      
  135.                                               
  136.                                         } catch(e)   
  137.                                         {  
  138.                                             jQuery.handleError(s, xml, null, e);  
  139.                                         }                                      
  140.  
  141.                                     }, 100)  
  142.  
  143.                 xml = null 
  144.  
  145.             }  
  146.         }  
  147.         // Timeout checker  
  148.         if ( s.timeout > 0 )   
  149.         {  
  150.             setTimeout(function(){  
  151.                 // Check to see if the request is still happening  
  152.                 if( !requestDone ) uploadCallback( "timeout" );  
  153.             }, s.timeout);  
  154.         }  
  155.         try   
  156.         {  
  157.            // var io = $('#' + frameId);  
  158.             var form = $('#' + formId);  
  159.             $(form).attr('action', s.url);  
  160.             $(form).attr('method', 'POST');  
  161.             $(form).attr('target', frameId);  
  162.             if(form.encoding)  
  163.             {  
  164.                 form.encoding = 'multipart/form-data';                  
  165.             }  
  166.             else  
  167.             {                  
  168.                 form.enctype = 'multipart/form-data';  
  169.             }              
  170.             $(form).submit();  
  171.  
  172.         } catch(e)   
  173.         {              
  174.             jQuery.handleError(s, xml, null, e);  
  175.         }  
  176.         if(window.attachEvent){  
  177.             document.getElementById(frameId).attachEvent('  
  178.         }  
  179.         else{  
  180.             document.getElementById(frameId).addEventListener('load', uploadCallback, false);  
  181.         }           
  182.         return {abort: function () {}};      
  183.  
  184.     },  
  185.  
  186.     uploadHttpData: function( r, type ) {  
  187.         var data = !type;  
  188.         data = type == "xml" || data ? r.responseXML : r.responseText;  
  189.         // If the type is "script", eval it in global context  
  190.         if ( type == "script" )  
  191.             jQuery.globalEval( data );  
  192.         // Get the JavaScript object, if JSON is used.  
  193.         if ( type == "json" )  
  194.             eval( "data = " + data );  
  195.         // evaluate scripts within html  
  196.         if ( type == "html" )  
  197.             jQuery("<div>").html(data).evalScripts();  
  198.             //alert($('param', data).each(function(){alert($(this).attr('value'));}));  
  199.         return data;  
  200.     }  
  201. }) 

三、纯iframe实现上传

upload.ashx

 

 
  
  1. 代码  
  2.  
  3. //<%@ WebHandler Language="C#" Class="upload" %> 
  4.  
  5. using System;  
  6. using System.Web;  
  7.  
  8. public class upload : IHttpHandler {  
  9.     private string Js(string v) {//此函数进行js的转义替换的,防止字符串中输入了'后造成回调输出的js中字符串不闭合  
  10.         if (v == null) return "";  
  11.         return v.Replace("'", @"\'");  
  12.     }  
  13.     //下面就是一个简单的示例,保存上传的文件,如果要验证上传的后缀名,得自己写,还有写数据库什么的  
  14.     public void ProcessRequest (HttpContext context) {  
  15.         HttpRequest Request = context.Request;  
  16.         HttpResponse Response = context.Response;  
  17.         HttpServerUtility Server = context.Server;  
  18.         //指定输出头和编码  
  19.         Response.ContentType = "text/html";  
  20.         Response.Charset = "utf-8";  
  21.           
  22.         HttpPostedFile f = Request.Files["upfile"];//获取上传的文件  
  23.         string des = Request.Form["des"]//获取描述  
  24.             ,newFileName=Guid.NewGuid().ToString();//使用guid生成新文件名  
  25.  
  26.         if (f.FileName == "")//未上传文件  
  27.             Response.Write("<script>parent.UpdateMsg('','');</script>");//输出js,使用parent对象得到父页的引用  
  28.         else { //保存文件  
  29.             newFileName += System.IO.Path.GetExtension(f.FileName);//注意加上扩展名  
  30.             try {  
  31.                 f.SaveAs(Server.MapPath("~/uploads/" + newFileName));//如果要保存到其他地方,注意修改这里  
  32.  
  33.                 //调用父过程更新内容,注意要对des变量进行js转义替换,防止字符串不闭合提示错误  
  34.                 Response.Write("<script>parent.UpdateMsg('" +Js(des)+ "','" + newFileName + "')</script>");  
  35.             }  
  36.             catch {  
  37.                 Response.Write("<script>alert('保存文件失败!\\n请检查文件夹是否有写入权限!');</script>");//如果保存失败,输出js提示保存失败  
  38.             }  
  39.               
  40.         }  
  41.     }  
  42.    
  43.     public bool IsReusable {  
  44.         get {  
  45.             return false;  
  46.         }  
  47.     }  
  48.  

test.htm

 

 
  
  1. 代码  
  2.  
  3. <!!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">> 
  4. <html xmlns="http://www.w3.org/1999/xhtml"> 
  5. <head> 
  6.     <meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
  7.     <title>使用隐藏的Iframe实现ajax无刷新上传</title> 
  8. </head> 
  9. <body> 
  10.     <script type="text/javascript"> 
  11.     function UpdateMsg(des,filename){//此函数用来提供给提交到的页面如upload.ashx输出js的回调,更新当前页面的信息  
  12.       if(filename==''){alert('未上传文件!');return false;}  
  13.       document.getElementById('ajaxMsg').innerHTML='你在表单中输入的“文件描述”为:'+des+'<br/>'  
  14.       +'上传的图片为:<a href="uploads/'+filename+'" target="_blank">'+filename+'</a>';  
  15.     }  
  16.       
  17.     function check(f){  
  18.       if(f.des.value==''){  
  19.          alert('请输入文件描述!');f.des.focus();return false;  
  20.       }  
  21.       if(f.upfile.value==''){  
  22.         alert('请选择文件!');f.upfile.focus();return false;  
  23.       }  
  24.     }  
  25.     </script>   
  26.     <!--隐藏的iframe来接受表单提交的信息--> 
  27.     <iframe name="ajaxifr" style="display:none;"></iframe> 
  28.     <!--这里设置target="ajaxifr",这样表单就提交到iframe里面了,和平时未设置target属性时默认提交到当前页面--> 
  29.     <!--注意一点的是使用iframe时在提交到的页面可以直接输出js来操作父页面的信息,一般的ajax提交文本信息时你需要返回信息,如果是js信息你还得eval下--> 
  30.     <form method="post" enctype="multipart/form-data" action="upload.ashx" target="ajaxifr" onsubmit="return check(this)"> 
  31.     文件描述:<input type="text" name="des" /><br > 
  32.     选择文件:<input type="file" name="upfile" /><br > 
  33.     <input type="submit" value="提交" /> 
  34.     </form> 
  35.     <!--放入此div用来实现上传的结果--> 
  36.     <div id="ajaxMsg"></div> 
  37. </body> 
  38. </html> 

本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1081584