ASP.NET程序上传文件功能代码

//asp.net 中上传文件的源代码,测试成功! using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; /// /// Summary description for UploadFile /// public class UploadFile { private string[] AllowFileType; //所允许的文件类型 private double FileLength; //所允许的文件大小(KB) private string SavePath; //文件的存储路径 private string SaveFile; //上传后的文件名 private string Error; //存储错误信息 private string FileExtesion; //上传文件的扩展名 /// /// 构造函数 /// /// 允许的文件类型,多个以","分开 /// 文件大小 /// 保存路径 public UploadFile(string allFileType, double fileLength, string savePath) { char[] sp = { ',' }; AllowFileType = allFileType.Split(sp); FileLength = fileLength * 1024; SavePath = savePath; } /// /// 返回生成的文件名 /// public string FileName { get { return SaveFile; } } /// /// 返回出错信息 /// public string ErrorMessage { get { return Error; } } /// /// 根据SavePath,生成文件名 /// /// private string MakeFileName(string fileType,string fileName) { string file = this.SavePath + "//" + DateTime.Now.ToString("yyMMddhhmmss") + fileName; while (File.Exists(file)) { file = this.SavePath + "//" + DateTime.Now.ToString("yyMMddhhmmss") + fileName; } return file; } /// /// 检查文件类型 /// /// MIME内容 /// private bool CheckFileExt(string fileEx) { bool result = false; for (int i = 0; i < this.AllowFileType.Length; i++) { if (fileEx.IndexOf(this.AllowFileType[i].ToLower()) > -1) { result = true; break; } } return result; } public bool UpLoad(System.Web.UI.WebControls.FileUpload file) { bool result = true; try { //查看文件长度 if (file.PostedFile.ContentLength > (this.FileLength)) { this.Error = "文件大小超出范允许的范围!"; return false; } string fileName = Path.GetFileName(file.PostedFile.FileName); this.FileExtesion = Path.GetExtension(fileName); if (!CheckFileExt(this.FileExtesion.ToLower())) { this.Error = "文件类型" + this.FileExtesion + "不允许!"; return false; } //取得要保存的文件名 string UpFile = this.MakeFileName(this.FileExtesion, fileName); //保存文件 file.PostedFile.SaveAs(UpFile); //返回文件名 this.SaveFile = Path.GetFileName(UpFile); } catch (Exception e) { result = false; this.Error = e.Message; } return result; } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值