效果圖
還有一個Js文件FielUpLoad.js
var i = 1 ; function AddFileToList(obj) { // 添加一行 var clientID = obj.parentElement.parentElement.parentElement.parentElement.id; var newTr = document.getElementById(clientID).insertRow(); // 添加两列 var newTd0 = newTr.insertCell(); var newTd1 = newTr.insertCell(); var newTd2 = newTr.insertCell(); // 设置列内容和属性 var file = document.createElement( " input " ); file.type = " file " ; file.id = file.name = " file " + i; file.name = " title " ; newTd0.appendChild(file); var btn = document.createElement( " input " ); btn.type = " button " ; btn.id = btn.name = " btn " + i; btn.value = " 移除 " ; btn.onclick = function () { var index = window.event.srcElement.parentElement.parentElement.rowIndex; document.getElementById(clientID).deleteRow(index); } newTd1.appendChild(btn); i++ ; return false ; }
設計文件FileUpLoad.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.IO; namespace FielUpLoad { [ToolboxData( " <{0}:FielUpLoad runat=server></{0}:FielUpLoad> " )] public class FielUpLoad : WebControl, INamingContainer { 屬性定義 #region 屬性定義 private Button btnAddFileToList; // 添加文件按鈕 private Button btnStartUpload; // 文件上傳按鈕 private HtmlInputFile hifFile; // 文件瀏覽控件 [Bindable(true )] [Category( " Appearance " )] [DefaultValue( 1048576 )] [Localizable( true )] [Description( " 文件總共最大的長度(單位KB)預設是1024*1024KB " )] public int TotalMaxFileLength { set { EnsureChildControls(); ViewState[ " TotalMaxFileLength " ] = value; } get { EnsureChildControls(); return ((ViewState[ " TotalMaxFileLength " ] == null ) ? 1048576 : ( int )ViewState[ " TotalMaxFileLength " ]); } } [Bindable(true )] [Category( " Appearance " )] [DefaultValue( 1024 )] [Localizable( true )] [Description( " 單個文件最大的長度(單位KB)預設是1024KB " )] public int SingleMaxFileLength { set { EnsureChildControls(); ViewState.Add( " SingleMaxFileLength " , value); } get { EnsureChildControls(); return ((ViewState[ " SingleMaxFileLength " ] == null ) ? 1024 : ( int )ViewState[ " SingleMaxFileLength " ]); } } [Category(" Appearance " ), Description( " 文件要存放的相對路徑如~\\存放在根目錄 " )] public string ServerFilePath { set { EnsureChildControls(); ViewState.Add( " ServerFilePath " , value); } get { EnsureChildControls(); String s = (String)ViewState[ " ServerFilePath " ]; return ((s == null ) ? " ~\\ " : s); } } [Bindable(true )] [Category( " Appearance " )] [DefaultValue( true )] [Localizable( true )] [Description( " 上傳文件名是否保留,還是重新產生 " )] public bool FileNameHold { set { EnsureChildControls(); ViewState.Add( " FileNameHold " ,value); } get { EnsureChildControls(); return ((ViewState[ " FileNameHold " ] == null ) ? true : ( bool )ViewState[ " FileNameHold " ]); } } #endregion 顯示消息的函數 #region 顯示消息的函數 /**/ /// <summary> /// 顯示消息的函數 /// </summary> /// <param name="java"></param> protected void ShowMessage( string sMessage) { Page.ClientScript.RegisterStartupScript( this .GetType(), " fsf " , " <script language=javascript>alert(' " + sMessage + " ');</script> " ); } #endregion 創建子控件 #region 創建子控件 /**/ /// <summary> /// 創建子控件 /// </summary> protected override void CreateChildControls() { Controls.Clear(); this .ServerFilePath = @" ~\ " ; hifFile = new HtmlInputFile(); hifFile.ID = " HtmlInputFilehifFile " ; btnAddFileToList = new Button(); btnAddFileToList.Text = " 添加 " ; btnAddFileToList.ID = " btnAddFileToList " ; btnAddFileToList.OnClientClick = " return AddFileToList(this) " ; btnStartUpload = new Button(); btnStartUpload.Text = " 上傳 " ; btnStartUpload.ID = " btnStartUpload " ; btnStartUpload.Click += new EventHandler(btnStartUpload_Click); this .Controls.Add(hifFile); this .Controls.Add(btnAddFileToList); this .Controls.Add(btnStartUpload); } #endregion 控件布局 #region 控件布局 /**/ /// <summary> /// 控件布局 /// </summary> /// <param name="writer"></param> protected override void Render(HtmlTextWriter writer) { EnsureChildControls();//這句好重要啊,我開始沒有這句,控件拖出來就有錯誤 AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); hifFile.RenderControl(writer); writer.RenderEndTag(); // Td writer.RenderBeginTag(HtmlTextWriterTag.Td); btnAddFileToList.RenderControl(writer); writer.RenderEndTag(); // Td writer.RenderBeginTag(HtmlTextWriterTag.Td); btnStartUpload.RenderControl(writer); writer.RenderEndTag(); // Td writer.RenderEndTag(); // Tr writer.RenderEndTag(); // Table } #endregion 重寫OnPreRender #region 重寫OnPreRender protected override void OnPreRender(EventArgs e) { if ( this .Page != null ) { this .Page.ClientScript.RegisterClientScriptResource( this .GetType(), " FielUpLoad.FielUpLoad.js " ); } base .OnPreRender(e); } #endregion 單擊按鈕上傳文件 #region 單擊按鈕上傳文件 /**/ /// <summary> /// 單擊按鈕上傳文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStartUpload_Click( object sender, System.EventArgs e) { SaveAs(); } #endregion 文件上傳另存為 #region 文件上傳另存為 /**/ /// <summary> /// 文件上傳另存為 /// </summary> /// <returns> 文件存放路徑以及文件名如:C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite2\ada\+20070302044811.jpg,20070302044811.jpg, </returns> public string SaveAs() { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; string sFileSavePath = GetAbsolutePath(@ServerFilePath); string sReturnFileName = sFileSavePath + " + " ; // 判斷文件大小是否超出 if ( ! IsAllowedLength()) return "" ; for ( int i = 0 ; i < files.Count; i ++ ) { if (files[i].FileName.Length > 0 ) { string sFileSavePathName = "" ; if (FileNameHold) sFileSavePathName = sFileSavePath + System.IO.Path.GetFileName(files[i].FileName); else sFileSavePathName = sFileSavePath + GetUniqueString() + i.ToString() + System.IO.Path.GetExtension(files[i].FileName); files[i].SaveAs(sFileSavePathName); sReturnFileName = sReturnFileName + System.IO.Path.GetFileName(sFileSavePathName) + " , " ; } } return sReturnFileName; } #endregion 根據相對路徑取得絕對路徑 #region 根據相對路徑取得絕對路徑 /**/ /// <summary> /// 根據相對路徑取得絕對路徑 /// </summary> /// <param name="sFilePath"> 相對路徑 </param> /// <returns></returns> private string GetAbsolutePath( string sFilePath) { try { // 取得絕對路徑 string sAbsolutePath = HttpContext.Current.Request.MapPath(sFilePath); // 判断路径是否存在,若不存在则创建路径 DirectoryInfo upDir = new DirectoryInfo(sAbsolutePath); if ( ! upDir.Exists) { upDir.Create(); } // 如果路径末尾为\符号,则直接返回路徑 if (sAbsolutePath.LastIndexOf( " \\ " ) != sAbsolutePath.Length) sAbsolutePath += " \\ " ; return sAbsolutePath; } catch { throw new Exception( " 由相對路徑取得絕對路徑失敗! " ); } } #endregion 获取一个不重复的文件名 #region 获取一个不重复的文件名 /**/ /// <summary> /// 获取一个不重复的文件名 /// </summary> /// <returns> 得到的文件名形如:20050922101010 </returns> private string GetUniqueString() { return DateTime.Now.ToString( " yyyyMMddhhmmss " ); } #endregion 判断上传文件大小是否合乎要求 #region 判断上传文件大小是否合乎要求 /**/ /// <summary> /// 判断上传文件大小是否合乎要求 /// </summary> /// <returns></returns> public bool IsAllowedLength() { bool bAllowed = true ; HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; double dTotalLength = 0 ; // 判斷上传文件的大小超过單個最大值 for ( int i = 0 ; i < files.Count; i ++ ) { if (files[i].ContentLength / 1024.0 > SingleMaxFileLength) { bAllowed = false ; ShowMessage( " 上傳文件失敗,單個文件超過允許最大值! " ); break ; } dTotalLength += files[i].ContentLength / 1024.0 ; } if (dTotalLength > TotalMaxFileLength) { bAllowed = false ; ShowMessage( " 上傳文件失敗,縂文件超過允許最大值! " ); } return bAllowed; } #endregion } }