首页 > 开发 > 综合 > 正文

一个文件上传的类

2024-07-21 02:16:33
字体:
来源:转载
供稿:网友
namespace wmj
{
public class myupload
{
private system.web.httppostedfile postedfile=null;
private string savepath="";
private string extension="";
private int filelength=0;
//显示该组件使用的参数信息
public string help
{
get{
string helpstring;
helpstring="<font size=3>myupload myupload=new myupload(); //构造函数";
helpstring+="myupload.postedfile=file1.postedfile;//设置要上传的文件";
helpstring+="myupload.savepath=/"e:///";//设置要上传到服务器的路径,默认c://";
helpstring+="myupload.filelength=100; //设置上传文件的最大长度,单位k,默认1k";
helpstring+="myupload.extension=/"doc/";设置上传文件的扩展名,默认txt";
helpstring+="label1.text=myupload.upload();//开始上传,并显示上传结果</font>";
helpstring+="<font size=3 color=red>design by wengmingjun 2001-12-12 all right reserved!</font>";
return helpstring;
}
}



public system.web.httppostedfile postedfile
{
get
{
return postedfile;
}
set
{
postedfile=value;
}
}



public string savepath
{
get
{
if(savepath!="") return savepath;
return "c://";
}
set
{
savepath=value;
}
}



public int filelength
{
get
{
if(filelength!=0) return filelength;
return 1024;
}
set
{
filelength=value*1024;
}
}



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);
}



public string upload()
{
if(postedfile!=null)
{
try{
string filename=pathtoname(postedfile.filename);
if(!filename.endswith(extension)) return "you must select "+extension+" file!";
if(postedfile.contentlength>filelength) return "file too big!";
postedfile.saveas(savepath+filename);
return "upload file successfully!";
}
catch(system.exception exc)
{return exc.message;}
}
return "please select a file to upload!";
}
}
}



用csc /target:library wmj.cs 编译成dll供以后多次调用
调用举例
<%@page language="c#" runat="server"%>
<%@import namespace="wmj"%>
<script language="c#" runat="server">
void upload(object sender,eventargs e)
{
myupload myupload=new myupload();
// label1.text=myupload.help;
myupload.postedfile=file1.postedfile;
myupload.savepath="e://";
myupload.filelength=100;
label1.text=myupload.upload();
}
</script>
<form enctype="multipart/form-data" runat="server">
<input type="file" id="file1" runat="server"/>
<asp:button id="button1" text="upload" onclick="upload" runat="server"/>
<asp:label id="label1" runat="server"/>
</form>
结论:asp.net的组件支持功能很强 我们如果充分利用可以很容易的编写出非常方便的组件可以大大的方便我们的工作


收集最实用的网页特效代码!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表