怎樣自定義一個服務(wù)器端的控件
2024-07-21 02:24:08
供稿:網(wǎng)友
大家知道在asp.net中微軟為我們提供了大量的服務(wù)器端控件,包括htmlcontrol 和webcontrol。它們功能強(qiáng)大,為我們的編程提供了極大的方便。更重要的一點(diǎn)是它開放了對第三方控件的使用。這就使我們可以定制自己需要的服務(wù)器端控件。
下面我就以一個集成化的上傳組件來說明怎樣自定義一個服務(wù)器端的控件,這個組件其實(shí)是htmlinputfile、button 和label以及事件實(shí)現(xiàn)的集合。這個組件要達(dá)到的功能是要象已有的webcontrol一樣,用一個設(shè)定了幾個屬性的標(biāo)記就自動可以實(shí)現(xiàn)文件上傳了,而不用再實(shí)現(xiàn)事件等。
編寫后端代碼編譯成一個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";
//上傳的文件保存在服務(wù)器上的位置默認(rèn)為c:/ 這些屬性一般都是在asp.net的標(biāo)記中設(shè)置也可以在codebehind中設(shè)置
public string savepath
{
get
{
if(savepath!="") return savepath;
return "c://";
}
set
{
savepath=value;
}
}
//上傳文件的最大長度 單位k 默認(rèn)為1k
public string filelength
{
get
{
if(filelength!="0") return filelength;
return "1024";
}
set
{
filelength=(int.parse(value)*1024).tostring();
}
}
//上傳文件的擴(kuò)展名 默認(rèn)為txt
public string extension
{
get
{
if(extension!="") return extension;
return "txt";
}
set
{
extension=value;
}
}
public string pathtoname(string path)
{
int pos=path.lastindexof("http://");
return path.substring(pos+1);
}
}
}
////////////////////////////////////////////////////////////////////////////////
////
將這個文件編譯成dl,l放在要使用位置的bin目錄下面就可以在網(wǎng)站中通過
<wmj:fileupload savepath="e://" filelength="3" extension="txt" runat="server"/>
使用這個組件了
下面舉個調(diào)用這個控件的例子
<%@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"/>
<!--怎么樣使用就是這么簡單有點(diǎn)一勞永逸的感覺了吧-->
</form>
</body>
</html>
有了這個例子的啟發(fā),大家再也不用擔(dān)心asp.net的服務(wù)器控件太少了吧。