一个简单的文件上传功能控件
2024-07-21 02:24:39
供稿:网友
总在用别人的控件,第一次想自己写个控件。于是写了个简单的小控件,主要是用于自己学习和其他想尝试写控件的朋友,请多多指教。
改控件主要作用是将本地图片上传到自定义目录。
using system;
using system.web.ui;
using system.web.ui.webcontrols;
using system.componentmodel;
using system.web.ui.htmlcontrols;
using system.io;
namespace uploadimage
{
/// <summary>
///作者:darkangel 2004-10-27日创建
///支持图片上传到服务器功能
/// </summary>
[defaultproperty("text"),
toolboxdata(@"<{0}:upimage runat=server></{0}:upimage>")]
public class upimage : control, inamingcontainer
{
protected int filelength;
protected string imageurl;
protected string mydirectory;
static string logourl;
protected string vpicture;
public button mybutton;
public htmlinputfile fileupload;
public label label1;
public upimage()
{
this.ensurechildcontrols();
}
[bindable(true),
category("appearance"),
defaultvalue("")]
[
descriptionattribute("文件大小")
]
public int filelength
{
set{filelength=value;}
get{return filelength;}
}
[
descriptionattribute("图片名字")
]
public string imageurl
{
set{imageurl=value;}
get{return imageurl;}
}
[
descriptionattribute("文件路径")
]
public string mydirectory
{
get{return mydirectory;}
set{mydirectory=value;}
}
[
descriptionattribute("图片的相对地址")
]
public string logo
{
get{return logourl;}
set{logourl=value;}
}
[
descriptionattribute("是否显示图片")
]
public string vpicture
{
set{vpicture=value;}
get{return vpicture;}
}
private void mybutton_click(object sender, system.eventargs e)
{
if(!fileupload.value.tostring().equals(""))
{
logourl=fileupload.postedfile.filename.tostring();
logourl=logourl.substring(logourl.lastindexof("."),(logourl.length-logourl.lastindexof(".")));
if(fileupload.postedfile.contentlength>filelength)
{
myscript("图片超过指定大小!");
}
else
{
if(logourl.equals(".jpg") || logourl.equals(".bmp") || logourl.equals(".gif"))
{
logourl=mydirectory+"//"+imageurl+logourl;
mydirectory=page.server.mappath(" ")+"//"+mydirectory;
if(directory.exists(mydirectory))
{
}
else
{
directory.createdirectory(mydirectory);
}
fileupload.postedfile.saveas(page.server.mappath(" ")+"//"+logourl);
if(vpicture.equals("1"))
{
label1.text="<img width='100' heigth='100' src='"+logourl+"'>";
}
myscript("图片上传成功!");
}
else
{
myscript("文件类型不对!");
}
}
}
}
protected void myscript(string java)
{
page.registerstartupscript("fsf","<script language=javascript>alert('"+java+"');</script>");
}
protected override void createchildcontrols()
{
mybutton=new button();
fileupload=new htmlinputfile();
label1=new label();
mybutton.text="提交";
this.controls.add(fileupload);
this.controls.add(mybutton);
this.controls.add(new literalcontrol("<p>"));
this.controls.add(label1);
this.controls.add(new literalcontrol("</p>"));
mybutton.click+=new eventhandler(mybutton_click);
}
}
}