本文共 3860 字,大约阅读时间需要 12 分钟。
/// <summary>
/// 文件上传的模块 /// </summary> public enum FileModelType { /// <summary> /// 头像 /// </summary> User, /// <summary> /// 产品图像 /// </summary> Product, /// <summary> /// 店铺banner /// </summary> ShopBanner, }/// <summary>
/// 上传警告 /// </summary> public enum UploadWarning { /// <summary> /// 大小错误 /// </summary> SizeError, /// <summary> /// 类型错误 /// </summary> TypeError, /// <summary> /// 扩展名错误 /// </summary> Extension, } /// <summary> /// 上传文件的基类,为实现上传的类提供公用的属性和方法 /// </summary> public abstract class UploadHelperBase { protected static string[] FileMIME = { "image/gif", "image/bmp", "image/pjpeg", "image/x-png" }; //要求的文件类型protected static Dictionary<FileModelType, string> RelativePath = new Dictionary<FileModelType, string> //字典对象来存储相对地位键值对的列表
{ {FileModelType.User,@"/user/"}, {FileModelType.Product,@"/product/"}, {FileModelType.ShopBanner,@"shopbanner/"}, };protected static string[] FileExtensions = { "jpg", "bmp", "gif", "png", "txt" }; //文件的扩展名
protected static Dictionary<UploadWarning, string> UploadError = new Dictionary<UploadWarning, string> //上传文件时的错误信息
{ {UploadWarning.SizeError,"大小错误,最大为{0}"}, {UploadWarning.TypeError,"类型错误"}, {UploadWarning.Extension,"扩展名错误"} }; }/// <summary>
/// 提供文件上传的实现 /// </summary> public class UploadFile : UploadHelperBase {#region 文件上传到本WWW服务器
public CommonMessage UploadImage(FileModelType modelType, HttpPostedFileBase hpf) { CommonMessage cMessage = new CommonMessage(); HttpRequest Request = HttpContext.Current.Request; if (this.IsFileViolation(modelType, hpf)) { string path = HttpContext.Current.Server.MapPath(RelativePath[modelType]); #region 目录如果不存在,就建立它 DirectoryInfo di = new DirectoryInfo(path); if (!di.Exists) di.Create(); #endregion string guid = Guid.NewGuid().ToString(); string filename = string.Format("{0}{1}", guid, new FileInfo(hpf.FileName).Extension);//上传文件的名称 hpf.SaveAs(string.Format("{0}{1}", path, filename)); cMessage.Clear(); cMessage.AddItem(string.Format("{0}://{1}{2}{3}", Request.Url.Scheme, Request.Url.Authority, RelativePath[modelType].Replace('\\', '/'), filename ) ); cMessage.AddItem(guid); cMessage.IsComplete = true; } else { cMessage.IsComplete = false; cMessage.AddItemRange(this.GetFileViolations(modelType, hpf)); } return cMessage; } #endregion#region 文件验证有效性
internal bool IsFileViolation(FileModelType modelType, HttpPostedFileBase file) { return GetFileViolations(modelType, file).Count() == 0; } /// <summary> /// 验证文件有效性,反回一个简单迭代 /// </summary> /// <param name="modelType"></param> /// <param name="file"></param> /// <returns></returns> internal IEnumerable<string> GetFileViolations(FileModelType modelType, HttpPostedFileBase file) { if (!FileMIME.Contains(file.ContentType)) yield return UploadError[UploadWarning.TypeError]; if (!FileExtensions.Contains(file.FileName.Remove(0, file.FileName.LastIndexOf('.') + 1).ToLower())) yield return UploadError[UploadWarning.Extension]; if (file.ContentLength > GetAllowSizeByFileModelType(modelType)) yield return string.Format(UploadError[UploadWarning.SizeError], GetAllowSizeByFileModelType(modelType) / 1000);}
#endregion#region 通过模块类型,得到被充许的容量大小
/// <summary> /// 通过文件模块类型,得到被指定的最大文件容量 /// </summary> /// <param name="modelType"></param> /// <returns></returns> int GetAllowSizeByFileModelType(FileModelType modelType) { switch (modelType) { case FileModelType.User: return 1000000; //1000KB break; case FileModelType.Product: return 2000000; break; case FileModelType.ShopBanner: return 3000000; break; default: throw new Exception("error"); break;}
} #endregion#region 获取Url文件名
/// <summary> /// 获取Url文件名 /// </summary> /// <param name="url">Url</param> /// <returns>Url文件名</returns> string GetUrlFileNameWithoutExtension(string url) { return System.IO.Path.GetFileNameWithoutExtension(url.Substring(url.LastIndexOf('/') + 1)); } #endregion}
本文转自博客园张占岭(仓储大叔)的博客,原文链接:,如需转载请自行联系原博主。