下面我就以一個集成化的上傳組件來說明怎樣自定義一個服務器端的控件,這個組件其實是HtmlInputFile、Button 和Label以及事件實現的集合。這個組件要達到的功能是要象已有的webcontrol一樣,用一個設定了幾個屬性的標記就自動可以實現文件上傳了,而不用再實現事件等。
編寫後端代碼編譯成一個dll
//文件名稱:WmjWebControls.cs
using System.Drawing;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System;
namespace Wmj
{
public class FileUpLoad : Panel
{
private HtmlInputFile htmlInputFile;
private Button button;
private Label label;
public FileUpLoad() : base()
{
htmlInputFile=new HtmlInputFile();
button=new Button();
button.Text="上傳";
button.Click+=new EventHandler(this.Button_Click);
label=new Label();
label.Text="<font size=2>請選擇上傳文件的路徑</font>";
this.Controls.Add(htmlInputFile);
this.Controls.Add(button);
this.Controls.Add(label);
this.Width=450;
this.Height=30;
this.BorderStyle=BorderStyle.Dotted;
this.BorderWidth=1;
}
private void Button_Click(object sender, EventArgs e)
{
System.Web.HttpPostedFile postedFile=htmlInputFile.PostedFile;
if(postedFile!=null)
{
try{
string fileName=PathToName(postedFile.FileName);
if(!fileName.EndsWith(Extension))
{label.Text="You must select "+Extension+" file!"; return;}
if(postedFile.ContentLength>int.Parse(FileLength))
{label.Text="File too big!";return;}
postedFile.SaveAs(SavePath+fileName);
label.Text="Upload File Successfully!";
return;
}catch(System.Exception exc){label.Text=exc.Message;return;}
}
label.Text="Please select a file to upload!";
return;
}
private string savePath="";
private string extension="";
private string fileLength="0";
//上傳的文件保存在服務器上的位置默認爲c:/ 這些屬性一般都是在asp.net的標記中設置也可以在codebehind中設置
public string SavePath
{
get
{
if(savePath!="") return savePath;
return "c://";
}
set
{
savePath=value;
}
}
//上傳文件的最大長度 單位k 默認爲1k
public string FileLength
{
get
{
if(fileLength!="0") return fileLength;
return "1024";
}
set
{
fileLength=(int.Parse(value)*1024).ToString();
}
}
//上傳文件的擴展名 默認爲txt
public string Extension
{
get
{
if(extension!="") return extension;
return "txt";
}
set
{
extension=value;
}
}
public string PathToName(string path)
{
int pos=path.LastIndexOf("//");
return path.Substring(pos+1);
}
}
}
////////////////////////////////////////////////////////////////////////////////
////
將這個文件編譯成dl,l放在要使用位置的bin目錄下面就可以在網站中通過
<Wmj:FileUpLoad SavePath="E://" FileLength="3" Extension="txt" runat="server"/>
使用這個組件了
下面舉個調用這個控件的例子
<%@page language="C#"%>
<!--注意下面這一句是必須的-->
<%@ Register TagPrefix="Wmj" Namespace="Wmj" Assembly="WmjWebControls"%>
<html>
<head>
</head>
<body>
<form enctype="multipart/form-data" runat="server">
<Wmj:FileUpLoad SavePath="E://" FileLength="3" Extension="txt" runat="server"/>
<!--怎麼樣使用就是這麼簡單有點一勞永逸的感覺了吧-->
</form>
</body>
</html>
有了這個例子的啓發,大家再也不用擔心asp.net的服務器控件太少了吧。