在 ASP.NET 開發的過程中,文件上傳往往使用自帶的 FileUpload 控件,可是用過的人都知道,這個控件的局限性十分大,最大的問題就在於上傳大文件時讓開發者尤為的頭疼,而且,上傳時無法方便的做到多線程的操控和上傳進度的顯示。筆者在此給大家推薦一款簡單易用的上傳組件,從而快速便捷得解決了 ASP.NET 中的大文件上傳問題。
首先,我們需要下載這個名為 RanUpLoad 的組件,可以去我的百度雲盤下載: http://pan.baidu.com/s/1ntuMpQT
下載完成之后,兩個 dll 文件添加到項目的引用中區,xml 文件也要復制在項目中的 bin 文件夾下,也就是最后三個文件都要存在於 bin 文件夾中。
接着,上傳控件還是用 ASP.NET 中自帶的 FileUpload 控件,需要添加的就是在 FileUpload 控件旁邊加入標簽:
<radU:RadProgressManager ID="Radprogressmanager1" Width="100%" runat="server" /> <radU:RadProgressArea ID="progressArea1" Width="100%" runat="server"></radU:RadProgressArea>
並且在 aspx 文件的起始處添加如下代碼:
<%@ Register TagPrefix="telerik" Namespace="Telerik.QuickStart" Assembly="Telerik.QuickStart" %> <%@ Register TagPrefix="radU" Namespace="Telerik.WebControls" Assembly="RadUpload.Net2" %>
當然,配置文件的 <system.web> 標簽中不能忘記下面這些語句:
<httpRuntime executionTimeout="3600" maxRequestLength="2097151" ></httpRuntime>
<httpModules> <add name="RadUploadModule" type="Telerik.WebControls.RadUploadHttpModule, RadUpload.Net2"/> </httpModules> <httpHandlers> <add verb="*" path="Telerik.RadUploadProgressHandler.aspx" type="Telerik.WebControls.RadUploadProgressHandler, RadUpload.Net2"></add> </httpHandlers>
現在,外部的輪廓都已經布好了,接下來就是點擊上傳之后服務器端所需的操作:
當然,做這些操作之前,我們先 using 一下 Telerik.WebControls 命名空間。
// 檢查文件 if (RadUploadContext.Current == null) { return; } if (RadUploadContext.Current.UploadedFiles.Count <= 0) { this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "MsgBox", "<script>alert('請選擇上傳文件 !')</script>"); return; } if (RadUploadContext.Current.UploadedFiles[0].ContentLength >= 2147483647) { this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "MsgBox", "<script>alert('上傳的文件不得超過 2GB !')</script>"); return; } UploadedFile file = RadUploadContext.Current.UploadedFiles[0]; string fileName = Path.GetFileName(file.FileName); string virtualPath = System.IO.Path.Combine("~/save", fileName); string savePath = this.MapPath(virtualPath); file.SaveAs(savePath, true);
至此,文件上傳的處理工作已經完成,以上的 cs 代碼是我自己的一些操作處理,大家可以根據自己情況酌情修改,比如也可以放置多個 FileUpload 控件,
用 foreach (UploadedFile file in RadUploadContext.Current.UploadedFiles) { ... } 這樣的方式處理多個文件的上傳。
希望此篇文章可以幫助對大文件上傳頭疼的朋友們去輕松處理上傳問題。
