文件上传无论在软件还是在网站上都十分常见,我今天再把它拿出来,讲一下,主要讲一下它的设计思想和实现技术,为了它的通用性,我把它做在了WEB.Service项目里,即它是针对服务器的,它的结构是关联UI(WEB)层与Service层(BLL)的桥梁.

结构

上传基类:

上传文件的接口规范:

接口的实现:

UI层调用WEB.Service层的上传功能:(附代码)

  1. public class FileUploadController : Controller
  2.  
  3. {
  4.  
  5. WEB.Services.IFileUpload iFileUpload = null;
  6.  
  7. public FileUploadController()
  8.  
  9. {
  10.  
  11. iFileUpload = new WEB.Services.FileUpload();
  12.  
  13. }
  14.  
  15. #region 文件上传
  16.  
  17. public ActionResult uploadheadpic()
  18.  
  19. {
  20.  
  21. return View();
  22.  
  23. }
  24.  
  25. [HttpPost]
  26.  
  27. public ActionResult uploadheadpic(FormCollection formcollection)
  28.  
  29. {
  30.  
  31. if (Request.Files.Count > 0)
  32.  
  33. {
  34.  
  35. HttpPostedFileBase file = Request.Files[0];
  36.  
  37. Entity.Commons.VMessage vm = iFileUpload.Image(WEB.Services.UpLoadType.DownloadUrl, file);
  38.  
  39. if (vm.IsComplete)
  40.  
  41. TempData["PicUrl"] = "{result:true,msg:\"" + vm[0].Replace("\"", "") + "\"}";
  42.  
  43. else
  44.  
  45. TempData["PicUrl"] = "{result:false,msg:\"" + vm[0].Replace("\"", "") + "\"}";
  46.  
  47. }
  48.  
  49. return View();
  50.  
  51. }
  52.  
  53. #endregion
  54.  
  55. }

下面公布一下上传的基类代码:(如果有设计不合理的地方,欢迎大家留言)

  1. namespace WEB.Services
  2.  
  3. {
  4.  
  5. #region 所需枚举
  6.  
  7. /// <summary>
  8.  
  9. /// 文件上传类型
  10.  
  11. /// </summary>
  12.  
  13. public enum UpLoadType
  14.  
  15. {
  16.  
  17. /// <summary>
  18.  
  19. /// 下载地址
  20.  
  21. /// </summary>
  22.  
  23. DownloadUrl = 0,
  24.  
  25. /// <summary>
  26.  
  27. /// 文件地址
  28.  
  29. /// </summary>
  30.  
  31. FileUrl = 1,
  32.  
  33. }
  34.  
  35. /// <summary>
  36.  
  37. /// 上传错误信息列举
  38.  
  39. /// </summary>
  40.  
  41. public enum WarnEnum
  42.  
  43. {
  44.  
  45. ImgContentType,
  46.  
  47. ImgContentLength,
  48.  
  49. ImgExtension,
  50.  
  51. }
  52.  
  53. #endregion
  54.  
  55. #region 文件上传基本服务类
  56.  
  57. /// <summary>
  58.  
  59. /// 文件上传基本服务类
  60.  
  61. /// </summary>
  62.  
  63. public abstract class FileUploadBase
  64.  
  65. {
  66.  
  67. /// <summary>
  68.  
  69. /// 图片MIME
  70.  
  71. /// </summary>
  72.  
  73. protected static List<string> imgMIME = new List<string>
  74.  
  75. {
  76.  
  77. "application/x-zip-compressed",
  78.  
  79. "application/octet-stream",
  80.  
  81. "application/x-compressed",
  82.  
  83. "application/x-rar-compressed",
  84.  
  85. "application/zip",
  86.  
  87. "application/vnd.ms-excel",
  88.  
  89. "application/vnd.ms-powerpoint",
  90.  
  91. "application/msword",
  92.  
  93. "image/jpeg",
  94.  
  95. "image/gif",
  96.  
  97. "audio/x-mpeg",
  98.  
  99. "audio/x-wma",
  100.  
  101. "application/x-shockwave-flash",
  102.  
  103. "video/x-ms-wmv",
  104.  
  105. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  106.  
  107. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  108.  
  109. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  110.  
  111. };
  112.  
  113. /// <summary>
  114.  
  115. /// 验证消息字典
  116.  
  117. /// </summary>
  118.  
  119. protected static Dictionary<WarnEnum, string> msgDIC = new Dictionary<WarnEnum, string>
  120.  
  121. {
  122.  
  123. {WarnEnum.ImgContentType ,"只能上传指定类型的文件!" },
  124.  
  125. {WarnEnum.ImgContentLength ,"只能上传文件大小为{0}以下!" },
  126.  
  127. {WarnEnum.ImgExtension , "文件的扩展文件不正确"}
  128.  
  129. };
  130.  
  131. /// <summary>
  132.  
  133. /// 相对地址字典
  134.  
  135. /// </summary>
  136.  
  137. protected static Dictionary<UpLoadType, string> relativePathDic = new Dictionary<UpLoadType, string>
  138.  
  139. {
  140.  
  141. {UpLoadType.DownloadUrl ,@"DownLoad/" },
  142.  
  143. {UpLoadType.FileUrl ,@"FileUpload/" },
  144.  
  145. };
  146.  
  147. /// <summary>
  148.  
  149. /// 图片后缀
  150.  
  151. /// </summary>
  152.  
  153. protected static string[] imgExtension = { "xls", "doc", "zip", "rar", "ppt", "docx", "xlsx", "pptx",
  154.  
  155. "mp3", "wma", "swf", "jpg", "jpeg", "gif" };
  156.  
  157. }
  158.  
  159. #endregion
  160.  
  161. }

文件上传实现类:

  1. public class FileUpload : FileUploadBase, IFileUpload
  2.  
  3. {
  4.  
  5. #region 文件上级WWW服务器及图像服务器
  6.  
  7. public Entity.Commons.VMessage Image(UpLoadType type, HttpPostedFileBase hpf)
  8.  
  9. {
  10.  
  11. HttpRequest Request = HttpContext.Current.Request;
  12.  
  13. Entity.Commons.VMessage vmsg = new Entity.Commons.VMessage();
  14.  
  15. if (this.IsIamgeVaild(type, hpf))
  16.  
  17. {
  18.  
  19. string relativePath = string.Format(VConfig.BaseConfigers.LocationUploadPath, relativePathDic[type]);
  20.  
  21. string path = HttpContext.Current.Server.MapPath(relativePath);
  22.  
  23. #region 建立路径
  24.  
  25. DirectoryInfo di = new DirectoryInfo(path);
  26.  
  27. if (!di.Exists)
  28.  
  29. {
  30.  
  31. di.Create();
  32.  
  33. }
  34.  
  35. #endregion
  36.  
  37. string guid = Guid.NewGuid().ToString();
  38.  
  39. string fileName = string.Format("{0}{1}", guid, new FileInfo(hpf.FileName).Extension);//上传文件的名称
  40.  
  41. hpf.SaveAs(string.Format("{0}{1}", path, fileName));
  42.  
  43. vmsg.Clear();
  44.  
  45. vmsg.AddItem(string.Format("{0}://{1}{2}{3}",
  46.  
  47. Request.Url.Scheme,
  48.  
  49. Request.Url.Authority,
  50.  
  51. relativePath.Replace('\\', '/'),
  52.  
  53. fileName
  54.  
  55. )
  56.  
  57. );
  58.  
  59. vmsg.AddItem(guid);
  60.  
  61. vmsg.IsComplete = true;
  62.  
  63. }
  64.  
  65. else
  66.  
  67. {
  68.  
  69. vmsg.AddItemRange(this.GetRuleViolations(type, hpf));
  70.  
  71. vmsg.IsComplete = false;
  72.  
  73. }
  74.  
  75. return vmsg;
  76.  
  77. }
  78.  
  79. public Entity.Commons.VMessage ImageToServer(string url)
  80.  
  81. {
  82.  
  83. Entity.Commons.VMessage vmsg = new Entity.Commons.VMessage();
  84.  
  85. Uri uri = new Uri(url);
  86.  
  87. string fileName = uri.Segments[uri.Segments.Length - 1];
  88.  
  89. string typeStr = uri.Segments[uri.Segments.Length - 2];
  90.  
  91. VCommons.Utils.FileUpLoad(
  92.  
  93. string.Format(BaseConfigers.DefaultUploadUri, typeStr.TrimEnd('/')),
  94.  
  95. HttpContext.Current.Server.MapPath(uri.LocalPath)
  96.  
  97. );
  98.  
  99. vmsg.IsComplete = true;
  100.  
  101. vmsg.AddItem(
  102.  
  103. string.Format("{0}://{1}/upload/{2}{3}",
  104.  
  105. HttpContext.Current.Request.Url.Scheme,
  106.  
  107. BaseConfigers.ImageServerHost,
  108.  
  109. typeStr,
  110.  
  111. fileName
  112.  
  113. )
  114.  
  115. );
  116.  
  117. return vmsg;
  118.  
  119. }
  120.  
  121. #endregion
  122.  
  123. #region 验证文件
  124.  
  125. internal bool IsIamgeVaild(UpLoadType type, HttpPostedFileBase hpf)
  126.  
  127. {
  128.  
  129. return this.GetRuleViolations(type, hpf).Count() == 0;
  130.  
  131. }
  132.  
  133. /// <summary>
  134.  
  135. /// 验证文件
  136.  
  137. /// </summary>
  138.  
  139. /// <param name="hpf"></param>
  140.  
  141. /// <returns></returns>
  142.  
  143. internal IEnumerable<string> GetRuleViolations(UpLoadType type, HttpPostedFileBase hpf)
  144.  
  145. {
  146.  
  147. if (!imgMIME.Contains(hpf.ContentType))// MIME
  148.  
  149. yield return msgDIC[WarnEnum.ImgContentType];
  150.  
  151. int contentLength = this.GetContentLengthByType(type);//文件大小
  152.  
  153. if (hpf.ContentLength > contentLength)
  154.  
  155. yield return string.Format(msgDIC[WarnEnum.ImgContentLength], contentLength / 1024);
  156.  
  157. if (!imgExtension.Contains(hpf.FileName.Substring(hpf.FileName.LastIndexOf('.') + 1)))//文件后缀
  158.  
  159. yield return msgDIC[WarnEnum.ImgExtension];
  160.  
  161. yield break;
  162.  
  163. }
  164.  
  165. #endregion
  166.  
  167. #region 根据 FileUpLoadContentLengthType 类型 获取相应的大小
  168.  
  169. /// <summary>
  170.  
  171. /// 根据 FileUpLoadContentLengthType 类型 获取相应的大小
  172.  
  173. /// </summary>
  174.  
  175. /// <param name="type">文件上传大小枚举值</param>
  176.  
  177. /// <returns>返回</returns>
  178.  
  179. int GetContentLengthByType(UpLoadType type)
  180.  
  181. {
  182.  
  183. switch (type)
  184.  
  185. {
  186.  
  187. case UpLoadType.DownloadUrl:
  188.  
  189. return 200000; //200M
  190.  
  191. case UpLoadType.FileUrl:
  192.  
  193. return 200000;
  194.  
  195. default:
  196.  
  197. throw new Exception("可能有错误");
  198.  
  199. }
  200.  
  201. }
  202.  
  203. #endregion
  204.  
  205. }

刚刚做了个文件上传功能,拿来分享一下!(MVC架构及传统架构通用)的更多相关文章

  1. MVC5:使用Ajax和HTML5实现文件上传功能

    引言 在实际编程中,经常遇到实现文件上传并显示上传进度的功能,基于此目的,本文就为大家介绍不使用flash 或任何上传文件的插件来实现带有进度显示的文件上传功能. 基本功能:实现带有进度条的文件上传功 ...

  2. Spring 文件上传功能

    本篇文章,我们要来做一个Spring的文件上传功能: 1. 创建一个Maven的web工程,然后配置pom.xml文件,增加依赖: <dependency> <groupId> ...

  3. Spring +SpringMVC 实现文件上传功能。。。

    要实现Spring +SpringMVC  实现文件上传功能. 第一步:下载 第二步: 新建一个web项目导入Spring 和SpringMVC的jar包(在MyEclipse里有自动生成spring ...

  4. 用c++开发基于tcp协议的文件上传功能

    用c++开发基于tcp协议的文件上传功能 2005我正在一家游戏公司做程序员,当时一直在看<Windows网络编程> 这本书,把里面提到的每种IO模型都试了一次,强烈推荐学习网络编程的同学 ...

  5. nodejs 实现简单的文件上传功能

    首先需要大家看一下目录结构,然后开始一点开始我们的小demo. 文件上传总计分为三种方式: 1.通过flash,activeX等第三方插件实现文件上传功能. 2.通过html的form标签实现文件上传 ...

  6. Android 实现文件上传功能(upload)

    文 件上传在B/S应用中是一种十分常见的功能,那么在Android平台下是否可以实现像B/S那样的文件上传功能呢?答案是肯定的.下面是一个模拟网站程 序上传文件的例子.这里只写出了Android部分的 ...

  7. Springboot如何启用文件上传功能

    网上的文章在写 "springboot文件上传" 时,都让你加上模版引擎,我只想说,我用不上,加模版引擎,你是觉得我脑子坏了,还是觉得我拿不动刀了. springboot如何启用文 ...

  8. PHPCMS_V9 模型字段添加单文件上传功能

    后台有“多文件上传”功能,但是对于有些情况,我们只需要上传一个文件,而使用多文件上传功能上传一个文件,而调用时调用一个文件URL太麻烦了. 使用说明: 1.打开phpcms\modules\conte ...

  9. 配置php.ini实现PHP文件上传功能

    本文介绍了如何配置php.ini实现PHP文件上传功能.其中涉及到php.ini配置文件中的upload_tmp_dir.upload_max_filesize.post_max_size等选项,这些 ...

随机推荐

  1. windows环境下Robot Framework的安装步骤

    Robot Framework是由python编写的开源的用来做功能性测试的自动化测试框架.本文介绍Robot Framework在windows环境下的安装步骤. 安装python从python官网 ...

  2. bash实现自动补全

    yum install -y bash-completion source /usr/share/bash-completion/bash_completion 执行后yum拥有选项自动补全功能 对于 ...

  3. DB2表空间

    https://www.ibm.com/developerworks/cn/data/library/techarticles/dm-0902yuancg/ 临时表空间的使用 (sorts or jo ...

  4. LeetCode(237)Delete Node in a Linked List

    题目 Write a function to delete a node (except the tail) in a singly linked list, given only access to ...

  5. xtu summer individual 2 D - Colliders

    Colliders Time Limit: 2000ms Memory Limit: 262144KB This problem will be judged on CodeForces. Origi ...

  6. Jquery跨域请求

    在JavaScript中,有一个很重要的安全性限制,被称为“Same- Origin Policy”(同源策略).这一策略对于JavaScript代码能够访问的页面内容做了很重要的限制,即JavaSc ...

  7. lubuntu通过Smb访问Windows共享目录

    lubuntu通过Smb访问Windows共享目录 如果未安装Smb,先安装: apt-get install smbclient smbfs 安装后,查看共享主机上的共享目录: CentOS/Red ...

  8. 那些“不务正业”的IT培训公司

    Before First 大四下期了,现在准备找一份Java开发的实习工作,于是在各大网站上投递简历-智联招聘.51job.拉勾网,慧眼识真金的我必然会把培训机构给过滤掉,对于重庆来说招聘实习的公司少 ...

  9. 【PD】PowerDesigner生成数据字典

    1.首先说明我使用的环境 --------------------------------第一种:不按模板导出导出数据字典----------------------------- 2.打开PDM模型 ...

  10. tomcat并发数

    Tomcat的最大并发数是可以配置的,实际运用中,最大并发数与硬件性能和CPU数量都有很大关系的.更好的硬件,更多的处理器都会使Tomcat支持更多的并发. Tomcat默认的HTTP实现是采用阻塞式 ...