文件上传无论在软件还是在网站上都十分常见,我今天再把它拿出来,讲一下,主要讲一下它的设计思想和实现技术,为了它的通用性,我把它做在了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架构及传统架构通用)的更多相关文章

  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. nginx 集群

    Nginx是什么? Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器.一直纳闷这个X是怎么来 ...

  2. tomcat 403错误和ls: cannot open directory '.': Permission denied

    在centos7 linux系统上使用docker进行tomcat部署项目测试的时候发现第一个错误:浏览器返回403 错误,显然是一个权限问题,禁止访问.下面是我一步一步的操作: 1 使用的docke ...

  3. h5 页面 禁止网页缩放

    //禁用双指缩放: document.documentElement.addEventListener('touchstart', function (event) { if (event.touch ...

  4. day22 02 面向对象的交互

    day22 02 面向对象的交互 一.三种编程方式 1.面向过程编程:核心是过程,流水线式思维 优点:极大降低了写程序的复杂程度,只需要顺着要执行的步骤,堆叠代码即可 缺点:一套流水线或者流程就用来解 ...

  5. Insertion or Heap Sort

    7-14 Insertion or Heap Sort(25 分) According to Wikipedia: Insertion sort iterates, consuming one inp ...

  6. 用cpp写对拍程序

    #include <bits/stdc++.h> using namespace std; int main() { while(true) { puts(""); p ...

  7. python和shell获取命令行参数的区别

    一.命令行参数的取得对于一些功能性的脚本来说非常有用,不至于将功能写死在脚本中. shell的命令行参数直接用 $ 1,$2 等就可以直接获取 其中 $1 表示 第二个参数,即命令行的第一个参数,因为 ...

  8. URAL 2040 Palindromes and Super Abilities 2

    Palindromes and Super Abilities 2Time Limit: 500MS Memory Limit: 102400KB 64bit IO Format: %I64d &am ...

  9. bzoj 1701 [Usaco2007 Jan]Cow School牛学校

    [Usaco2007 Jan]Cow School牛学校 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 175  Solved: 83[Submit][S ...

  10. msp430项目编程24

    msp430中项目---MMC接口 1.串行通信工作原理 2.串行通信协议 3.代码(显示部分) 4.代码(功能实现) 5.项目总结 msp430项目编程 msp430入门学习