分类:
2008-10-15 16:36:51
public class CUploadFile
{
///
/// 该类实现了文件上传功能,需要指定HtmlInputFile 控件
/// 功能1:可以对文件类型进行限制
/// 功能2:可以对文件大小上限进行限制
///
/// example:
/// CUploadFile up;
/// up = new CUploadFile(HtmlInputFile1);
/// up.SvaePath = "c:\\inetpub\\wwwroot\\upload\\"; //必须指定,保存文件的路径
/// up.AllowExtFile = ".jpg;.gif;"; //允许的类型
/// up.MaxSize = 500 * 1024; //大小限制500k
/// up.NewFileName = "newfile1"; //指定新的文件名,不指定则不修改
/// int errcode = up.Start(); //开始上传
/// string errmsg = up.GetErr(errcode); //获得错误描述信息
/// Response.write(errmsg); //显示错误信息
///
System.Web.UI.HtmlControls.HtmlInputFile _scrfile;//HtmlInputFile 控件
string _savepath = "";//保存文件的路径
string _newfilename = "";//文件重命名为
string _newextfile = "";//文件后缀
int _maxsize = 0;//文件大小限制
string _extfile = "";//允许的后缀名,用“;”分割,包含“.”,为空时允许全部文件类型
//构造函数,不指定任何数据
public CUploadFile() { } |
//构造函数,指定了HtmlInputFile 控件
public CUploadFile(System.Web.UI.HtmlControls.HtmlInputFile scrFile) { this.FileSource = scrFile; } |
//构造函数,指定了HtmlInputFile 控件、保存路径,文件名不作修改
public CUploadFile(System.Web.UI.HtmlControls.HtmlInputFile scrFile, string SavePath) { this.FileSource = scrFile; _savepath = SavePath; _newfilename = scrFile.PostedFile.FileName; } |
//构造函数,指定了HtmlInputFile 控件、保存路径、新的文件名(不包含后缀)
public CUploadFile(System.Web.UI.HtmlControls.HtmlInputFile scrFile, string SavePath,string NewFileName) { this.FileSource = scrFile; _savepath = SavePath; _newfilename = NewFileName; } |
//准备就绪后,开始上传
public int Start() { if(_scrfile.PostedFile.ContentLength == 0) { return 504; //no source } else if((_scrfile.PostedFile.ContentLength >= _maxsize)&&(_maxsize != 0)) { return 501; //out of the range } else if((_savepath == "")||(_newfilename == "")) { return 505; //no filename or path } else if(!CheckExt()) { return 502; //ext is not allow } try { _scrfile.PostedFile.SaveAs(_savepath + _newfilename + _newextfile); return 0; } catch { return 500; //unknow error } } |
[1]