asp.net实现文件上传带进度条(多种风格)

来源:互联网 发布:淘宝做单一个月挣多少 编辑:程序博客网 时间:2024/05/17 09:20

文件上传 带进度条 多种风格 非常漂亮!

asp.net实现文件上传带进度条(多种风格)

 

 

 

 

友好的提示 以及上传验证!

 

 

 

 

 

部分代码:

 

[c-sharp] view plaincopy
  1. <%@ Page Language="C#" %>  
  2. <%@ Register Assembly="MattBerseth.WebControls.AJAX" Namespace="MattBerseth.WebControls.AJAX.Progress" TagPrefix="mb" %>  
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5.   
  6. <html xmlns="http://www.w3.org/1999/xhtml">  
  7. <head runat="server">  
  8.     <title>Untitled Page</title>  
  9.     <link rel="Stylesheet" href="_assets/css/progress.css" mce_href="_assets/css/progress.css" />  
  10.     <link rel="Stylesheet" href="_assets/css/upload.css" mce_href="_assets/css/upload.css" />  
  11.     <mce:style type="text/css"><!--  
  12.         BODY{ font-family:Arial, Sans-Serif; font-size:12px;}  
  13.       
  14. --></mce:style><style type="text/css" mce_bogus="1">        BODY{ font-family:Arial, Sans-Serif; font-size:12px;}  
  15.     </style>  
  16.     <mce:script type="text/C#" runat="server"><!--  
  17.          
  18.         protected void Page_Load(object sender, EventArgs args)  
  19.         {  
  20.             if (!this.IsPostBack)  
  21.             {                  
  22.                 this.Session["UploadInfo"] = new UploadInfo { IsReady = false };  
  23.             }  
  24.         }  
  25.           
  26.         /// <summary>  
  27.         ///   
  28.         /// </summary>  
  29.         [System.Web.Services.WebMethod]  
  30.         [System.Web.Script.Services.ScriptMethod]  
  31.         public static object GetUploadStatus()  
  32.         {  
  33.             //获取文件长度  
  34.             UploadInfo info = HttpContext.Current.Session["UploadInfo"as UploadInfo;  
  35.   
  36.             if (info != null && info.IsReady)  
  37.             {  
  38.                 int soFar = info.UploadedLength;  
  39.                 int total = info.ContentLength;  
  40.   
  41.                 int percentComplete = (int)Math.Ceiling((double)soFar / (double)total * 100);  
  42.                 string message = string.Format("上传 {0} ... {1} of {2} 字节", info.FileName, soFar, total);  
  43.                   
  44.                 //  返回百分比  
  45.                 return new { percentComplete = percentComplete, message = message };  
  46.             }  
  47.   
  48.             //  还没有准备好...  
  49.             return null;  
  50.         }  
  51.       
  52.       
  53. // --></mce:script>  
  54. </head>  
  55. <body>  
  56.     <form id="form1" runat="server">  
  57.     <asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />  
  58.       
  59.     <mce:script type="text/javascript"><!--  
  60.         var intervalID = 0;  
  61.         var progressBar;  
  62.         var fileUpload;  
  63.         var form;         
  64.         // 进度条        
  65.         function pageLoad(){             
  66.             $addHandler($get('upload'), 'click', onUploadClick);  
  67.             progressBar = $find('progress');  
  68.         }  
  69.         // 注册表单         
  70.         function register(form, fileUpload){              
  71.             this.form = form;  
  72.             this.fileUpload = fileUpload;  
  73.         }          
  74.         //上传验证  
  75.         function onUploadClick() {          
  76.             var vaild = fileUpload.value.length > 0;  
  77.             if(vaild){                
  78.                 $get('upload').disabled = 'disabled';               
  79.                 updateMessage('info''初始化上传...');                  
  80.                 //提交上传  
  81.                 form.submit();                  
  82.                 // 隐藏frame  
  83.                 Sys.UI.DomElement.addCssClass($get('uploadFrame'), 'hidden');  
  84.                 // 0开始显示进度条  
  85.                 progressBar.set_percentage(0);  
  86.                 progressBar.show();             
  87.                 // 上传过程  
  88.                 intervalID = window.setInterval(function(){  
  89.                     PageMethods.GetUploadStatus(function(result){  
  90.                         if(result){  
  91.                             //  更新进度条为新值  
  92.                             progressBar.set_percentage(result.percentComplete);  
  93.                             //更新信息  
  94.                             updateMessage('info', result.message);  
  95.                               
  96.                             if(result == 100){  
  97.                                 // 自动消失  
  98.                                 window.clearInterval(intervalID);                          
  99.                             }  
  100.                         }  
  101.                     });  
  102.                 }, 500);                  
  103.             }  
  104.             else{  
  105.                 onComplete('error''您必需选择一个文件');  
  106.             }  
  107.         }         
  108.       
  109.         function onComplete(type, msg){  
  110.             // 自动消失  
  111.             window.clearInterval(intervalID);  
  112.             // 显示消息  
  113.             updateMessage(type, msg);  
  114.             // 隐藏进度条  
  115.             progressBar.hide();  
  116.             progressBar.set_percentage(0);  
  117.             // 重新启用按钮  
  118.             $get('upload').disabled = '';  
  119.             //  显示frame  
  120.             Sys.UI.DomElement.removeCssClass($get('uploadFrame'), 'hidden');  
  121.         }          
  122.         function updateMessage(type, value){  
  123.             var status = $get('status');  
  124.             status.innerHTML = value;  
  125.             // 移除样式  
  126.             status.className = '';  
  127.             Sys.UI.DomElement.addCssClass(status, type);  
  128.         }  
  129.       
  130.       
  131. // --></mce:script>  
  132.       
  133.     <div>  
  134.         <div class="upload">  
  135.             <h3>文件上传</h3>  
  136.             <div>  
  137.                 <iframe id="uploadFrame" frameborder="0" scrolling="no" src="Upload.aspx" mce_src="Upload.aspx"></iframe>  
  138.                 <mb:ProgressControl ID="progress" runat="server" CssClass="lightblue" style="display:none" mce_style="display:none" Value="0" Mode="Manual" Speed=".4" Width="100%" />  
  139.                 <div>  
  140.                     <div id="status" class="info">请选择要上传的文件</div>  
  141.                     <div class="commands">  
  142.                         <input id="upload" type="button" value="上传" />   
  143.                     </div>  
  144.                 </div>  
  145.             </div>  
  146.         </div>   
  147.         
  148.     </div>  
  149.     </form>  
  150. </body>  
  151. </html>  

 

upload.aspx:

[c-sharp] view plaincopy
  1. //限制大小 1M  
  2.         protected void Page_Load2(object sender, EventArgs e)  
  3.         {  
  4.             if (this.IsPostBack)  
  5.             {  
  6.                 UploadInfo uploadInfo = this.Session["UploadInfo"as UploadInfo;  
  7.                 if (uploadInfo == null)  
  8.                 {  
  9.                     // 让父页面知道无法处理上传  
  10.                     const string js = "window.parent.onComplete('error', '无法上传文件。请刷新页面,然后再试一次);";  
  11.                     ScriptManager.RegisterStartupScript(thistypeof(upload_aspx), "progress", js, true);  
  12.                 }  
  13.                 else  
  14.                 {  
  15.                     //  让服务端知道我们还没有准备好..  
  16.                     uploadInfo.IsReady = false;  
  17.   
  18.                     //  上传验证  
  19.                     if (this.fileUpload.PostedFile != null && this.fileUpload.PostedFile.ContentLength > 0  
  20.   
  21.                         && this.fileUpload.PostedFile.ContentLength < 1048576)//  限制1M  
  22.                     {  
  23.                         //  设置路径  
  24.                         string path = this.Server.MapPath(@"Uploads");  
  25.                         string fileName = Path.GetFileName(this.fileUpload.PostedFile.FileName);  
  26.   
  27.                         // 上传信息  
  28.                         uploadInfo.ContentLength = this.fileUpload.PostedFile.ContentLength;  
  29.                         uploadInfo.FileName = fileName;  
  30.                         uploadInfo.UploadedLength = 0;  
  31.   
  32.                        //文件存在 初始化...  
  33.                         uploadInfo.IsReady = true;  
  34.   
  35.                        //缓存  
  36.                         int bufferSize = 1;  
  37.                         byte[] buffer = new byte[bufferSize];  
  38.   
  39.                         // 保存字节  
  40.                         using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))  
  41.                         {                           
  42.                             while (uploadInfo.UploadedLength < uploadInfo.ContentLength)  
  43.                             {  
  44.                                //从输入流放进缓冲区  
  45.                                 int bytes = this.fileUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);  
  46.                                 // 字节写入文件流  
  47.                                 fs.Write(buffer, 0, bytes);  
  48.                                 //  更新大小  
  49.                                 uploadInfo.UploadedLength += bytes;  
  50.   
  51.                                 //  线程睡眠 上传就更慢 这样就可以看到进度条了  
  52.                                 System.Threading.Thread.Sleep(100);  
  53.                             }  
  54.                         }  
  55.   
  56.                         // 删除.  
  57.                         File.Delete(Path.Combine(path, fileName));  
  58.   
  59.                         //   让父页面知道已经处理上传完毕  
  60.                         const string js = "window.parent.onComplete('success', '{0} 已成功上传');";  
  61.                         ScriptManager.RegisterStartupScript(thistypeof(upload_aspx), "progress"string.Format(js, fileName), true);  
  62.                     }  
  63.                     else  
  64.                     {  
  65.                         if (this.fileUpload.PostedFile.ContentLength >= 1048576)//1M  
  66.                         {  
  67.                             const string js = "window.parent.onComplete('error', '超出上传文件限制大小,请重新选择');";  
  68.                             ScriptManager.RegisterStartupScript(thistypeof(upload_aspx), "progress", js, true);  
  69.                         }  
  70.                         else  
  71.                         {  
  72.                             const string js = "window.parent.onComplete('error', '上传文件出错');";  
  73.                             ScriptManager.RegisterStartupScript(thistypeof(upload_aspx), "progress", js, true);  
  74.                         }  
  75.                     }                    
  76.                     uploadInfo.IsReady = false;  
  77.                 }  
  78.             }          
  79.         }  
  80.   
  81.         // 不限制大小  
  82.         protected void Page_Load(object sender, EventArgs e)  
  83.         {  
  84.             if (this.IsPostBack)  
  85.             {  
  86.                 UploadInfo uploadInfo = this.Session["UploadInfo"as UploadInfo;               
  87.                 uploadInfo.IsReady = false;                 
  88.                 if (this.fileUpload.PostedFile != null && this.fileUpload.PostedFile.ContentLength > 0)  
  89.                 {                 
  90.                     string path = this.Server.MapPath(@"Uploads");  
  91.                     string fileName = Path.GetFileName(this.fileUpload.PostedFile.FileName);  
  92.                      
  93.                     uploadInfo.ContentLength = this.fileUpload.PostedFile.ContentLength;  
  94.                     uploadInfo.FileName = fileName;  
  95.                     uploadInfo.UploadedLength = 0;  
  96.                       
  97.                     uploadInfo.IsReady = true;  
  98.   
  99.                     int bufferSize = 1;  
  100.                     byte[] buffer = new byte[bufferSize];  
  101.   
  102.                     using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))  
  103.                     {  
  104.                         while (uploadInfo.UploadedLength < uploadInfo.ContentLength)  
  105.                         {  
  106.                             int bytes = this.fileUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);                            
  107.                             fs.Write(buffer, 0, bytes);                           
  108.                             uploadInfo.UploadedLength += bytes;  
  109.                         }  
  110.                     }  
  111.                     const string js = "window.parent.onComplete('success', '{0} 已成功上传');";  
  112.                     ScriptManager.RegisterStartupScript(thistypeof(upload_aspx), "progress"string.Format(js, fileName), true);  
  113.                 }  
  114.                 else  
  115.                 {  
  116.                     const string js = "window.parent.onComplete('error', '上传文件出错');";  
  117.                     ScriptManager.RegisterStartupScript(thistypeof(upload_aspx), "progress", js, true);  
  118.                 }  
  119.                 uploadInfo.IsReady = false;  
  120.             }  
  121.         }          

0 0
原创粉丝点击