刚刚做了个文件上传功能,拿来分享一下!(MVC架构及传统架构通用)
文件上传无论在软件还是在网站上都十分常见,我今天再把它拿出来,讲一下,主要讲一下它的设计思想和实现技术,为了它的通用性,我把它做在了WEB.Service项目里,即它是针对服务器的,它的结构是关联UI(WEB)层与Service层(BLL)的桥梁.
结构
上传基类:
上传文件的接口规范:
接口的实现:
UI层调用WEB.Service层的上传功能:(附代码)
public class FileUploadController : Controller { WEB.Services.IFileUpload iFileUpload = null; public FileUploadController() { iFileUpload = new WEB.Services.FileUpload(); } #region 文件上传 public ActionResult uploadheadpic() { return View(); } [HttpPost] public ActionResult uploadheadpic(FormCollection formcollection) { if (Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files[0]; Entity.Commons.VMessage vm = iFileUpload.Image(WEB.Services.UpLoadType.DownloadUrl, file); if (vm.IsComplete) TempData["PicUrl"] = "{result:true,msg:\"" + vm[0].Replace("\"", "") + "\"}"; else TempData["PicUrl"] = "{result:false,msg:\"" + vm[0].Replace("\"", "") + "\"}"; } return View(); } #endregion }
下面公布一下上传的基类代码:(如果有设计不合理的地方,欢迎大家留言)
namespace WEB.Services { #region 所需枚举 /// <summary> /// 文件上传类型 /// </summary> public enum UpLoadType { /// <summary> /// 下载地址 /// </summary> DownloadUrl = 0, /// <summary> /// 文件地址 /// </summary> FileUrl = 1, } /// <summary> /// 上传错误信息列举 /// </summary> public enum WarnEnum { ImgContentType, ImgContentLength, ImgExtension, } #endregion #region 文件上传基本服务类 /// <summary> /// 文件上传基本服务类 /// </summary> public abstract class FileUploadBase { /// <summary> /// 图片MIME /// </summary> protected static List<string> imgMIME = new List<string> { "application/x-zip-compressed", "application/octet-stream", "application/x-compressed", "application/x-rar-compressed", "application/zip", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "application/msword", "image/jpeg", "image/gif", "audio/x-mpeg", "audio/x-wma", "application/x-shockwave-flash", "video/x-ms-wmv", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.openxmlformats-officedocument.presentationml.presentation", }; /// <summary> /// 验证消息字典 /// </summary> protected static Dictionary<WarnEnum, string> msgDIC = new Dictionary<WarnEnum, string> { {WarnEnum.ImgContentType ,"只能上传指定类型的文件!" }, {WarnEnum.ImgContentLength ,"只能上传文件大小为{0}以下!" }, {WarnEnum.ImgExtension , "文件的扩展文件不正确"} }; /// <summary> /// 相对地址字典 /// </summary> protected static Dictionary<UpLoadType, string> relativePathDic = new Dictionary<UpLoadType, string> { {UpLoadType.DownloadUrl ,@"DownLoad/" }, {UpLoadType.FileUrl ,@"FileUpload/" }, }; /// <summary> /// 图片后缀 /// </summary> protected static string[] imgExtension = { "xls", "doc", "zip", "rar", "ppt", "docx", "xlsx", "pptx", "mp3", "wma", "swf", "jpg", "jpeg", "gif" }; } #endregion }
文件上传实现类:
public class FileUpload : FileUploadBase, IFileUpload { #region 文件上级WWW服务器及图像服务器 public Entity.Commons.VMessage Image(UpLoadType type, HttpPostedFileBase hpf) { HttpRequest Request = HttpContext.Current.Request; Entity.Commons.VMessage vmsg = new Entity.Commons.VMessage(); if (this.IsIamgeVaild(type, hpf)) { string relativePath = string.Format(VConfig.BaseConfigers.LocationUploadPath, relativePathDic[type]); string path = HttpContext.Current.Server.MapPath(relativePath); #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)); vmsg.Clear(); vmsg.AddItem(string.Format("{0}://{1}{2}{3}", Request.Url.Scheme, Request.Url.Authority, relativePath.Replace('\\', '/'), fileName ) ); vmsg.AddItem(guid); vmsg.IsComplete = true; } else { vmsg.AddItemRange(this.GetRuleViolations(type, hpf)); vmsg.IsComplete = false; } return vmsg; } public Entity.Commons.VMessage ImageToServer(string url) { Entity.Commons.VMessage vmsg = new Entity.Commons.VMessage(); Uri uri = new Uri(url); string fileName = uri.Segments[uri.Segments.Length - 1]; string typeStr = uri.Segments[uri.Segments.Length - 2]; VCommons.Utils.FileUpLoad( string.Format(BaseConfigers.DefaultUploadUri, typeStr.TrimEnd('/')), HttpContext.Current.Server.MapPath(uri.LocalPath) ); vmsg.IsComplete = true; vmsg.AddItem( string.Format("{0}://{1}/upload/{2}{3}", HttpContext.Current.Request.Url.Scheme, BaseConfigers.ImageServerHost, typeStr, fileName ) ); return vmsg; } #endregion #region 验证文件 internal bool IsIamgeVaild(UpLoadType type, HttpPostedFileBase hpf) { return this.GetRuleViolations(type, hpf).Count() == 0; } /// <summary> /// 验证文件 /// </summary> /// <param name="hpf"></param> /// <returns></returns> internal IEnumerable<string> GetRuleViolations(UpLoadType type, HttpPostedFileBase hpf) { if (!imgMIME.Contains(hpf.ContentType))// MIME yield return msgDIC[WarnEnum.ImgContentType]; int contentLength = this.GetContentLengthByType(type);//文件大小 if (hpf.ContentLength > contentLength) yield return string.Format(msgDIC[WarnEnum.ImgContentLength], contentLength / 1024); if (!imgExtension.Contains(hpf.FileName.Substring(hpf.FileName.LastIndexOf('.') + 1)))//文件后缀 yield return msgDIC[WarnEnum.ImgExtension]; yield break; } #endregion #region 根据 FileUpLoadContentLengthType 类型 获取相应的大小 /// <summary> /// 根据 FileUpLoadContentLengthType 类型 获取相应的大小 /// </summary> /// <param name="type">文件上传大小枚举值</param> /// <returns>返回</returns> int GetContentLengthByType(UpLoadType type) { switch (type) { case UpLoadType.DownloadUrl: return 200000; //200M case UpLoadType.FileUrl: return 200000; default: throw new Exception("可能有错误"); } } #endregion }
本文转自博客园张占岭(仓储大叔)的博客,原文链接:刚刚做了个文件上传功能,拿来分享一下!(MVC架构及传统架构通用),如需转载请自行联系原博主。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
谈谈软件的开发及成长历程
每个人身上,都有着独一无二的经历,也有着不一样的成长历程。回顾一下,从大学时期参加校网络中心从事开发工作,到目前在社会上的风雨兼程,也走过十多年的开发路程了,黄金岁月,青春年华,都在这期间度过。 养成经常写写博客的习惯,也将近10年,每篇文章,都体现自己某一刻的体会或者想法,博客十年,也是自己的技术十年,总结了无数的开发心得和开发思路,或者有时候也很欣喜的介绍一下自己的劳动成果,辛苦与愉悦,伴随着时间慢慢沉淀。 由于热衷技术的原因,博客内容一般围绕某个技术点,或者某个主题进行介绍,逐渐也形成了几个内容较多的标签,也是自己一直以来坚持的成果,回首过去,还是能看到沉淀下来的一些成绩。 1、代码生成工具的探索 虽然05年就注册加入了博客园,不过05年正处于奔波忙碌的年代,在上海的一家外资公司做软件外包的开发工作,公司管理严格,禁止发送任何信息到外面,因此多数情况下在休息时间看看一些文章,了解一些技术的动态,自己业余时间则主要沉醉于第二版代码生成工具的开发工作,之前的第一版主要是在C#代码中糅合了需要生成的代码,能解决一些工作,但维护的工作量很大,容易出错。因此后来碰到了NVelocity的模...
- 下一篇
利用Database2Sharp生成的EnterpriseLibrary架构的特点
框架的主要特点: 1)基于N层架构分层思想,各层边界清晰,可维护性更好。 2)基于最为广泛接受的RBAC(Role Based Access Control )的权限模型,控制更强、更合理。 3)遵循省移动公司统一UI样式、统一框架、集中授权、集成省公司相关业务组件(如工作流、日志等) 4)使用代码生成工具辅助开发,70%以上的代码可直接生成。 5)页面呈现组件化,代码更少、开发更快、界面更统一。 N层架构分层 使用了N层架构技术,分界面层、业务逻辑层、数据访问层、实体层;界面做了封装、底层数据使用企业库组件处理。 业务处理边界更加清晰,代码可读性、可维护性更好 使用更加稳定成熟C# 2.0的.NET框架,底层支持更多 使用了泛型技术,减少数据的装箱拆箱,强类型数据更加安全,性能更高。 基于泛型的基类封装技术,代码重用性更高 使用了Asp.net 2.0的Master Page页面技术。 使用参数化Sql操作数据库,业务数据更安全 权限控制模型 基于最为广泛接受的RBAC(Role Based Access Control )的权限模型,权限控制更加合理和规范,粒度更细,安全性更好。...
相关文章
文章评论
共有0条评论来说两句吧...