【无私分享:从入门到精通ASP.NET MVC】从0开始,一起搭框架、做项目 (11)文件管理

索引

【无私分享:从入门到精通ASP.NET MVC】从0开始,一起搭框架、做项目 目录索引

简述

文件管理,这个比较鸡肋 但是有些方法 大家可以参考下

项目准备

我们用的工具是:VS 2013 + SqlServer 2012 + IIS7.5

希望大家对ASP.NET MVC有一个初步的理解,理论性的东西我们不做过多解释,有些地方不理解也没关系,会用就行了,用的多了,用的久了,自然就理解了。

项目开始

其实叫文件管理呢有点过,这个功能比较鸡肋,但是大家可以参考一下一些方法

一、我们在ComManage区域下面新建个控制器 UploadControllers

1、1 我们新建一个视图Home,这里接收的fileExt就是左侧用户选择的文件类型

 1 /// <summary>
 2         /// 文件管理默认页面
 3         /// </summary>
 4         /// <returns></returns>
 5         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "View")]
 6         public ActionResult Home()
 7         {
 8             var fileExt = Request.QueryString["fileExt"] ?? "";
 9             ViewData["fileExt"] = fileExt;
10             return View();
11         }

1、2 我们新建一个获取获取文件的方法 然后试图页通过ajax获取数据

 1 /// <summary>
 2         /// 通过路径获取所有文件
 3         /// </summary>
 4         /// <returns></returns>
 5         public ActionResult GetAllFileData()
 6         {
 7             string fileExt = Request.Form["fileExt"];
 8             var jsonM = new JsonHelper() { Status = "y", Msg = "success" };
 9             try
10             {
11                 var images = ConfigurationManager.AppSettings["Image"].Trim(',').Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => "." + p).ToList();
12                 var videos = ConfigurationManager.AppSettings["Video"].Trim(',').Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => "." + p).ToList();
13                 var musics = ConfigurationManager.AppSettings["Music"].Trim(',').Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => "." + p).ToList();
14                 var documents = ConfigurationManager.AppSettings["Document"].Trim(',').Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => "." + p).ToList();
15 
16                 switch(fileExt)
17                 {
18                     case "images":   
19                     
20                         jsonM.Data = Common.Utils.DataTableToList<FileModel>(FileHelper.GetAllFileTable(Server.MapPath(ConfigurationManager.AppSettings["uppath"]))).OrderByDescending(p => p.name).Where(p=>images.Any(e=>e==p.ext)).ToList();
21                         break;
22                     case "videos":
23                        
24                         jsonM.Data = Common.Utils.DataTableToList<FileModel>(FileHelper.GetAllFileTable(Server.MapPath(ConfigurationManager.AppSettings["uppath"]))).OrderByDescending(p => p.name).Where(p => videos.Any(e => e == p.ext)).ToList();
25                         break;
26                     case "musics":
27                        
28                         jsonM.Data = Common.Utils.DataTableToList<FileModel>(FileHelper.GetAllFileTable(Server.MapPath(ConfigurationManager.AppSettings["uppath"]))).OrderByDescending(p => p.name).Where(p => musics.Any(e => e == p.ext)).ToList();
29                         break;
30                     case "files":
31                        
32                         jsonM.Data = Common.Utils.DataTableToList<FileModel>(FileHelper.GetAllFileTable(Server.MapPath(ConfigurationManager.AppSettings["uppath"]))).OrderByDescending(p => p.name).Where(p => documents.Any(e => e == p.ext)).ToList();
33                         break;
34                     case "others":
35 
36                         jsonM.Data = Common.Utils.DataTableToList<FileModel>(FileHelper.GetAllFileTable(Server.MapPath(ConfigurationManager.AppSettings["uppath"]))).OrderByDescending(p => p.name).Where(p => !images.Contains(p.ext) && !videos.Contains(p.ext) && !musics.Contains(p.ext) && !documents.Contains(p.ext)).ToList();
37                         break;
38                     default:
39                         jsonM.Data = Common.Utils.DataTableToList<FileModel>(FileHelper.GetAllFileTable(Server.MapPath(ConfigurationManager.AppSettings["uppath"]))).OrderByDescending(p => p.name).ToList();
40                         break;
41                 }
42                 
43             }
44             catch (Exception)
45             {
46                 jsonM.Status = "err";
47                 jsonM.Msg = "获取文件失败!";
48             }
49             return Content(JsonConverter.Serialize(jsonM, true));
50         }      

1、3 FileModel模型

 1 /// <summary>
 2         /// 文件名称
 3         /// </summary>
 4         public string name { get; set; }
 5         /// <summary>
 6         /// 文件全称
 7         /// </summary>
 8         public string fullname { get; set; }
 9         /// <summary>
10         /// 文件路径
11         /// </summary>
12         public string path { get; set; }
13         /// <summary>
14         /// 文件格式
15         /// </summary>
16         public string ext { get; set; }
17         /// <summary>
18         /// 文件大小
19         /// </summary>
20         public string size { get; set; }
21         /// <summary>
22         /// 文件图标
23         /// </summary>
24         public string icon { get; set; }
25         /// <summary>
26         /// 是否为文件夹
27         /// </summary>
28         public bool isfolder { get; set; }
29         /// <summary>
30         /// 是否为图片
31         /// </summary>
32         public bool isImage { get; set; }
33         /// <summary>
34         /// 上传时间
35         /// </summary>
36         public DateTime time { get; set; }

1、4 FileHelper类GetAllFileTable方法 我们把获得的文件数据转换成DataTable 返回回来

 1 /// <summary>
 2         /// 获取目录下所有文件(包含子目录)
 3         /// </summary>
 4         /// <param name="Path"></param>
 5         /// <returns></returns>
 6 
 7         public static DataTable GetAllFileTable(string Path)
 8         {
 9             DataTable dt = new DataTable();
10             dt.Columns.Add("name", typeof(string));
11             dt.Columns.Add("ext", typeof(string));
12             dt.Columns.Add("size", typeof(string));
13             dt.Columns.Add("icon", typeof(string));
14             dt.Columns.Add("isfolder", typeof(bool));
15             dt.Columns.Add("isImage", typeof(bool));
16             dt.Columns.Add("fullname", typeof(string));
17             dt.Columns.Add("path", typeof(string));
18             dt.Columns.Add("time", typeof(DateTime));
19 
20             string[] folders = Directory.GetDirectories(Path, "*", SearchOption.AllDirectories);
21 
22             List<string> Listfloders = new List<string>() { Path };
23 
24             if (folders != null && folders.Count() > 0)
25             {
26                 foreach (var folder in folders)
27                 {
28                     Listfloders.Add(folder);
29                 }
30             }
31 
32             foreach (var f in Listfloders)
33             {
34                 DirectoryInfo dirinfo = new DirectoryInfo(f);
35                 FileInfo fi;
36                 string FileName = string.Empty, FileExt = string.Empty, FileSize = string.Empty, FileIcon = string.Empty, FileFullName = string.Empty, FilePath = string.Empty;
37                 bool IsFloder = false, IsImage = false;
38                 DateTime FileModify;
39                 try
40                 {
41                     foreach (FileSystemInfo fsi in dirinfo.GetFiles())
42                     {
43 
44                         fi = (FileInfo)fsi;
45                         //获取文件名称
46                         FileName = fi.Name.Substring(0, fi.Name.LastIndexOf('.'));
47                         FileFullName = fi.Name;
48                         //获取文件扩展名
49                         FileExt = fi.Extension.ToLower();
50                         //获取文件大小
51                         FileSize = GetDiyFileSize(fi);
52                         //获取文件最后修改时间
53                         FileModify = fi.LastWriteTime;
54                         //文件图标
55                         FileIcon = GetFileIcon(FileExt);
56                         //是否为图片
57                         IsImage = IsImageFile(FileExt.Substring(1, FileExt.Length - 1));
58                         //文件路径
59                         FilePath = urlconvertor(fi.FullName);
60 
61                         DataRow dr = dt.NewRow();
62                         dr["name"] = FileName;
63                         dr["fullname"] = FileFullName;
64                         dr["ext"] = FileExt;
65                         dr["size"] = FileSize;
66                         dr["time"] = FileModify;
67                         dr["icon"] = FileIcon;
68                         dr["isfolder"] = IsFloder;
69                         dr["isImage"] = IsImage;
70                         dr["path"] = FilePath;
71                         dt.Rows.Add(dr);
72                     }
73                 }
74                 catch (Exception e)
75                 {
76 
77                     throw e;
78                 }
79             }
80 
81             return dt;
82         }

1、5 展示文件列表

我用了个jquery.tmpl.js插件 大家可以用比较流行的 angularjs

这个JS包含了 加载文件列表、删除单个文件、删除多个文件、显示文件路径、复制文件、移动文件、压缩文件、解压文件等方法 我们待会分别把方法列出来

  1 $(function () {
  2     filesManage.initFiles();    
  3 });
  4 var filesManage = {
  5     initFiles: function () {
  6         $.post("/Com/Upload/GetAllFileData", { fileExt: $("#fileExt").val() }, function (res) {
  7             if (res.Status == "y") {
  8                 if (res.Data == "" || res.Data == null) {
  9                     $("#filesPanel").html('<div class="alert alert-warning text-center"><span style="font-size:16px;"><i class="fa fa-warning"></i>&nbsp;没有找到任何文件</span></div>');
 10                 } else {
 11                     $("#filesPanel").empty();
 12                     $("#tlist").tmpl(res.Data).appendTo('#filesPanel');
 13                     $(".file-box").each(function () { animationHover(this, "pulse") });
 14                     //初始化CheckBox
 15                     $(".icheck_box").iCheck({
 16                         checkboxClass: 'icheckbox_flat-red',
 17                         radioClass: 'iradio_flat-red',
 18                         increaseArea: '20%' // optional
 19                     });
 20                     //点击选中/取消
 21                     $(".checkselected").click(function () {
 22                         if ($(this).parent().next().find('input[name="check_files"]').prop("checked"))
 23                         {
 24                             $(this).parent().next().find('input[name="check_files"]').iCheck("uncheck");
 25                         }
 26                         else {
 27                             $(this).parent().next().find('input[name="check_files"]').iCheck("check");
 28                         }
 29                     });
 30                 }
 31             } 
 32             else {
 33                 dig.error(res.Msg);
 34             }
 35         }, "json");
 36     },
 37     delFiles: function (n) {
 38         dig.confirm("删除确认", "删除后不可恢复,确定删除吗?", function () {
 39             $.post("/Com/Upload/DeleteBy", { path: n }, function (res) {
 40                 if (res.Status == "y")
 41                     location.reload();
 42                 else {
 43                     dig.error(res.Msg);
 44                 }
 45             }, "json");
 46         });
 47     },
 48     delMoreFiles: function () {
 49         var vals = '';
 50         $('input[name="check_files"]:checked').each(function () {
 51             vals += $(this).val() + ';';
 52         });
 53         if (vals == '' || vals == ';') {
 54             dig.error("对不起,请选中您要操作的文件!");
 55             return;
 56         }
 57         dig.confirm("删除确认", "删除后不可恢复,确定删除吗?", function () {
 58             $.post("/Com/Upload/DeleteBy", { path: vals }, function (res) {
 59                 if (res.Status == "y")
 60                     location.reload();
 61                 else {
 62                     dig.error(res.Msg);
 63                 }
 64             }, "json");
 65         });
 66     },
 67     showFilePath: function (n) {
 68         dig.msg("","文件目录:"+n);
 69     },
 70     copyFiles: function () {
 71         var vals = '';
 72         $('input[name="check_files"]:checked').each(function () {
 73             vals += $(this).val() + ';';
 74         });
 75         if (vals == '' || vals == ';') {
 76             dig.error("对不起,请选中您要操作的文件!");
 77             return;
 78         }
 79         dig.fileOperation('',vals,"/Com/Upload/Copy", function () {
 80             if (this.returnValue == 'yes') {
 81                 location.reload();
 82             }
 83         });
 84     },
 85     moveFiles: function () {
 86         var vals = '';
 87         $('input[name="check_files"]:checked').each(function () {
 88             vals += $(this).val() + ';';
 89         });
 90         if (vals == '' || vals == ';') {
 91             dig.error("对不起,请选中您要操作的文件!");
 92             return;
 93         }
 94         dig.fileOperation('', vals, "/Com/Upload/Cut", function () {
 95             if (this.returnValue == 'yes') {
 96                 location.reload();
 97             }
 98         });
 99     },
100     compressFiles: function () {
101         var vals = '';
102         $('input[name="check_files"]:checked').each(function () {
103             vals += $(this).val() + ';';
104         });
105         if (vals == '' || vals == ';') {
106             dig.error("对不起,请选中您要操作的文件!");
107             return;
108         }
109         dig.fileOperation('', vals, "/Com/Upload/Compress", function () {
110             if (this.returnValue == 'yes') {
111                 location.reload();
112             }
113         });
114     },
115     expandFiles: function () {
116         var vals = '';
117         var num = 0;
118         $('input[name="check_files"]:checked').each(function () {
119             vals = $(this).val();
120             num++;
121         });
122         if (!vals) {
123             dig.error("对不起,请选中您要操作的文件!");
124             return;
125         }
126         if (num > 1) {
127             dig.error("对不起,每次只能操作一个文件!");
128             return;
129         }
130         if(vals.substring(vals.lastIndexOf('.'), vals.length)!=".zip")
131         {
132             dig.error("只能解压ZIP格式文件!");
133             return;
134         }
135         dig.fileOperation('', vals, "/Com/Upload/Expand", function () {
136             if (this.returnValue == 'yes') {
137                 location.reload();
138             }
139         });
140     }
141 };
142 function animationHover(o, e) {
143     o = $(o), o.hover(function () {
144         o.addClass("animated " + e)
145     }, function () {
146         window.setTimeout(function () {
147             o.removeClass("animated " + e)
148         }, 2e3)
149     })
150 }

 

二、文件操作

2、1 删除文件或文件夹

 1 /// <summary>
 2         /// 删除文件或文件夹
 3         /// </summary>
 4         /// <returns></returns>
 5         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Remove")]
 6         public ActionResult DeleteBy()
 7         {
 8             var jsonM = new JsonHelper() { Status = "y", Msg = "success" };
 9             try
10             {
11                 var path = Request.Form["path"].Trim(';').Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p).ToList();
12 
13                 foreach (var file in path)
14                 {
15                     //删除文件
16                     FileHelper.DeleteFile(Server.MapPath(file));
17                 }
18 
19                 WriteLog(Common.Enums.enumOperator.Remove, "删除文件:" + path, Common.Enums.enumLog4net.WARN);
20             }
21             catch (Exception ex)
22             {
23                 jsonM.Status = "err";
24                 jsonM.Msg = "删除过程中发生错误!";
25                 WriteLog(Common.Enums.enumOperator.Remove, "删除文件发生错误:", ex);
26             }
27             return Json(jsonM);
28         }

2、2 复制文件到文件夹

 1 /// <summary>
 2         /// 复制文件到文件夹
 3         /// </summary>
 4         /// <returns></returns>
 5         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Copy")]
 6         public ActionResult Copy(string files)
 7         {
 8             ViewData["Files"] = files;
 9             ViewData["spath"] = ConfigurationManager.AppSettings["uppath"];
10             return View();
11         }
12         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Copy")]
13         public ActionResult CopyFiles()
14         {
15             var json = new JsonHelper() { Msg = "复制文件完成", Status = "n" };
16 
17             try
18             {
19                 var files = Request.Form["files"].Trim(';').Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p).ToList();
20                 var path = Request.Form["path"];
21                 foreach (var file in files)
22                 {
23                     FileHelper.Copy(Server.MapPath(file), Server.MapPath(path) + FileHelper.GetFileName(Server.MapPath(file)));
24                 }
25                 WriteLog(Common.Enums.enumOperator.None, "复制文件:" + Request.Form["files"].Trim(';') + ",结果:" + json.Msg, Common.Enums.enumLog4net.WARN);
26                 json.Status = "y";
27             }
28             catch(Exception e)
29             {
30                 json.Msg = "复制文件失败!";
31                 WriteLog(Common.Enums.enumOperator.None, "复制文件:", e);
32             }
33 
34             return Json(json);
35         }

2、3 移动文件到文件夹

 1 /// <summary>
 2         /// 移动文件到文件夹
 3         /// </summary>
 4         /// <returns></returns>
 5         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Cut")]
 6         public ActionResult Cut(string files)
 7         {
 8             ViewData["Files"] = files;
 9             ViewData["spath"] = ConfigurationManager.AppSettings["uppath"];
10             return View();
11         }
12         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Cut")]
13         public ActionResult CutFiles()
14         {
15             var json = new JsonHelper() { Msg = "移动文件完成", Status = "n" };
16 
17             try
18             {
19                 var files = Request.Form["files"].Trim(';').Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p).ToList();
20                 var path = Request.Form["path"];
21                 foreach (var file in files)
22                 {
23                     FileHelper.Move(Server.MapPath(file), Server.MapPath(path));
24                 }
25                 WriteLog(Common.Enums.enumOperator.None, "移动文件:" + Request.Form["files"].Trim(';') + ",结果:" + json.Msg, Common.Enums.enumLog4net.WARN);
26                 json.Status = "y";
27             }
28             catch (Exception e)
29             {
30                 json.Msg = "移动文件失败!";
31                 WriteLog(Common.Enums.enumOperator.None, "移动文件:", e);
32             }
33 
34             return Json(json);
35         }

2、4 压缩文件

 1 /// <summary>
 2         /// 压缩文件
 3         /// </summary>
 4         /// <returns></returns>
 5         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Compress")]
 6         public ActionResult Compress(string files)
 7         {
 8             ViewData["Files"] = files;
 9             ViewData["spath"] = ConfigurationManager.AppSettings["uppath"];
10             return View();
11         }
12         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Compress")]
13         public ActionResult CompressFiles()
14         {
15             var json = new JsonHelper() { Msg = "压缩文件完成", Status = "n" };
16 
17             try
18             {
19                 var files = Request.Form["files"].Trim(';').Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p).ToList();
20                 var path = Request.Form["path"];
21                 foreach (var file in files)
22                 {
23                     ZipHelper.ZipFile(Server.MapPath(file), Server.MapPath(path));
24                 }
25                 //ZipHelper.ZipDirectory(Server.MapPath("/upload/files/"), Server.MapPath(path));
26                 WriteLog(Common.Enums.enumOperator.None, "压缩文件:" + Request.Form["files"].Trim(';') + ",结果:" + json.Msg, Common.Enums.enumLog4net.WARN);
27                 json.Status = "y";
28             }
29             catch (Exception e)
30             {
31                 json.Msg = "压缩文件失败!";
32                 WriteLog(Common.Enums.enumOperator.None, "压缩文件:", e);
33             }
34 
35             return Json(json);
36         }

2、5 解压文件

 1 /// <summary>
 2         /// 解压文件
 3         /// </summary>
 4         /// <returns></returns>
 5         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Expand")]
 6         public ActionResult Expand(string files)
 7         {
 8             ViewData["Files"] = files;
 9             ViewData["spath"] = ConfigurationManager.AppSettings["uppath"];
10             return View();
11         }
12         [UserAuthorizeAttribute(ModuleAlias = "Files", OperaAction = "Expand")]
13         public ActionResult ExpandFiles()
14         {
15             var json = new JsonHelper() { Msg = "解压文件完成", Status = "n" };
16 
17             try
18             {
19                 var files = Request.Form["files"];
20                 var path = Request.Form["path"];
21                 var password = Request.Form["password"];
22 
23                 if (string.IsNullOrEmpty(password))
24                 {
25                     json.Msg = "请输入解压密码!";
26                     return Json(json);
27                 }
28 
29                 string CurrentPassword=ConfigurationManager.AppSettings["ZipPassword"] != null ? new Common.CryptHelper.AESCrypt().Decrypt(ConfigurationManager.AppSettings["ZipPassword"].ToString()) : "guodongbudingxizhilang";
30 
31                 if (password != CurrentPassword)
32                 {
33                     json.Msg = "解压密码无效!";
34                     return Json(json);
35                 }
36                
37                 ZipHelper.UnZip(Server.MapPath(files), Server.MapPath(path),password);
38                 
39                 WriteLog(Common.Enums.enumOperator.None, "解压文件:" + Request.Form["files"].Trim(';') + ",结果:" + json.Msg, Common.Enums.enumLog4net.WARN);
40                 json.Status = "y";
41             }
42             catch (Exception e)
43             {
44                 json.Msg = "解压文件失败!";
45                 WriteLog(Common.Enums.enumOperator.None, "解压文件:", e);
46             }
47 
48             return Json(json);
49         }

 

关于压缩和解压文件 我用的是ICSharpCode.SharpZipLib 有不太了解的朋友可以参考一下:ICSharpCode.SharpZipLib 压缩、解压文件 附源码

 

三、单文件上传

3、1 我们建一个上传视图页

1 /// <summary>
2         /// 单文件上传视图
3         /// </summary>
4         /// <returns></returns>
5         public ActionResult FileMain()
6         {
7             ViewData["spath"] = ConfigurationManager.AppSettings["uppath"];
8             return View();
9         }

3、2 试图页的Js

  1 $(function () {
  2     //获取IFrame传递过来的值
  3     var dialog = top.dialog.get(window);
  4     var data = dialog.data;
  5     $("#fileUrl").val(data);
  6     if (data != '' && data != undefined) {
  7         //文件定位
  8         var p = data.substring(0, data.lastIndexOf('/') + 1);
  9         $('#path').val(p);
 10         $('#jsons').val('{"path":"' + data + '"}');
 11     }
 12     signfiles.initFiles($("#path").val());
 13     //上传
 14     $(".sign-upload").click(function () {
 15         $("#fileUp").unbind();
 16         $("#fileUp").click();
 17     });
 18     //保存
 19     $(".btn-save").click(function () {
 20         dialog.close($("#jsons").val());
 21         dialog.remove();
 22     });
 23     //返回上级目录
 24     $(".btn-higher-up").click(function () {
 25         signfiles.OpenParentFolder();
 26     });
 27 });
 28 var signfiles = {
 29     signUpFile: function (upInput) {
 30         var subUrl = "/Com/Upload/SignUpFile?fileUp=fileUrl&isThumbnail=" + $("#isThumbnail").prop("checked") + "&isWater=" + $("#isWater").prop("checked");
 31         $("#forms").ajaxSubmit({
 32             beforeSubmit: function () {
 33                 dig.loading("正在上传");
 34                 $(".sign-upload").attr("disabled", "disabled");
 35             },
 36             success: function (data) {
 37                 if (data.Status == "y") {
 38                     var res = eval('(' + data.Data + ')');
 39                     $('#fileUrl').val(res.path);
 40                     $('#jsons').val(data.Data);
 41                     //定位
 42                     var pa = res.path.substring(0, res.path.lastIndexOf('/') + 1);
 43                     $('#path').val(pa);
 44                     signfiles.initFiles(pa);
 45                     sweetAlert.close();
 46                 } else {
 47                     dig.error(data.Msg);
 48                 }
 49                 $(".sign-upload").attr("disabled", false);
 50 
 51             },
 52             error: function (e) {
 53                 sweetAlert.close();
 54                 $(".sign-upload").attr("disabled", false);
 55                 console.log(e);
 56             },
 57             url: subUrl,
 58             type: "post",
 59             dataType: "json",
 60             timeout: 600000
 61         });
 62     },
 63     initFiles: function (path) {
 64         if (path == $("#spath").val()) {
 65             $(".btn-higher-up").attr("disabled", "disabled");
 66         } else {
 67             $(".btn-higher-up").attr("disabled", false);
 68         }
 69         $.post("/Com/Upload/GetFileData", { path: path }, function (res) {
 70             if (res.Status == "y") {
 71                 if (res.Data == "" || res.Data == null) {
 72                     dig.error("该目录下没有文件了!");
 73                     signfiles.OpenParentFolder();
 74                 } else {
 75                     $("#filesPanel").empty();
 76                     $("#tlist").tmpl(res.Data).appendTo('#filesPanel');
 77                 }
 78             } else if (res.Status == "empty") {
 79                 $("#filesPanel").html('<div class="alert alert-warning text-center"><span style="font-size:16px;"><i class="fa fa-warning"></i>&nbsp;没有找到任何文件</span></div>');
 80             }
 81             else {
 82                 dig.error(res.Msg);
 83             }
 84         }, "json");
 85     },
 86     OpenFolder: function (path) {
 87         var npath = $("#path").val() + path + "/";
 88         $("#path").val(npath);
 89         signfiles.initFiles(npath);
 90     },
 91     OpenParentFolder: function () {
 92         var p = $("#path").val();
 93         if (p == $("#spath").val()) return;
 94         p = p.substring(0, p.lastIndexOf('/'));
 95         p = p.substring(0, p.lastIndexOf('/')) + "/";
 96         $("#path").val(p);
 97         signfiles.initFiles(p);
 98     },
 99     SetFile: function (path, ext,size,name) {
100         $("#fileUrl").val($("#path").val() + path);
101         $('#jsons').val('{"path":"' + $("#path").val() + path + '","thumbpath":"' + $("#path").val() + "thumb_" + path + ' ","ext":"' + ext + '","unitsize":"' + size + '","newname":"' + name + '","oldname":"' + name + '"}');
102     }
103 }

3、3 单文件上传方法

 1  /// <summary>
 2         /// 单个文件上传
 3         /// </summary>
 4         [HttpPost]
 5         public ActionResult SignUpFile()
 6         {
 7             var jsonM = new JsonHelper() { Status = "n", Msg = "success" };
 8             try
 9             {
10                 //取得上传文件
11                 HttpPostedFileBase upfile = Request.Files["fileUp"];
12 
13                 //原始文件路径
14                 string delpath = Request.QueryString["delpath"];
15 
16                 //缩略图
17                 bool isThumbnail = string.IsNullOrEmpty(Request.QueryString["isThumbnail"]) ? false : Request.QueryString["isThumbnail"].ToLower() == "true" ? true : false;
18                 //水印
19                 bool isWater = string.IsNullOrEmpty(Request.QueryString["isWater"]) ? false : Request.QueryString["isWater"].ToLower() == "true" ? true : false;
20 
21 
22                 if (upfile == null)
23                 {
24                     jsonM.Msg = "请选择要上传文件!";
25                     return Json(jsonM);
26                 }
27                 jsonM = FileSaveAs(upfile, isThumbnail, isWater);
28 
29                 #region 移除原始文件
30                 if (jsonM.Status == "y" && !string.IsNullOrEmpty(delpath))
31                 {
32                     if (System.IO.File.Exists(Utils.GetMapPath(delpath)))
33                     {
34                         System.IO.File.Delete(Utils.GetMapPath(delpath));
35                     }
36                 }
37                 #endregion
38 
39                 if (jsonM.Status == "y")
40                 {
41                     #region 记录上传数据
42                     string unit = string.Empty;
43                     var jsonValue = Common.JsonConverter.ConvertJson(jsonM.Data.ToString());
44                     var entity = new Domain.COM_UPLOAD()
45                     {
46                         ID = Guid.NewGuid().ToString(),
47                         FK_USERID = this.CurrentUser.Id.ToString(),
48                         UPOPEATOR = this.CurrentUser.Name,
49                         UPTIME = DateTime.Now,
50                         UPOLDNAME = jsonValue.oldname,
51                         UPNEWNAME = jsonValue.newname,
52                         UPFILESIZE = FileHelper.GetDiyFileSize(long.Parse(jsonValue.size), out unit),
53                         UPFILEUNIT = unit,
54                         UPFILEPATH = jsonValue.path,
55                         UPFILESUFFIX = jsonValue.ext,
56                         UPFILETHUMBNAIL = jsonValue.thumbpath,
57                         UPFILEIP = Utils.GetIP(),
58                         UPFILEURL = "http://" + Request.Url.AbsoluteUri.Replace("http://", "").Substring(0, Request.Url.AbsoluteUri.Replace("http://", "").IndexOf('/'))
59                     };
60                     this.UploadManage.Save(entity);
61                     #endregion
62 
63                     #region 返回文件信息
64                     jsonM.Data = "{\"oldname\": \"" + jsonValue.oldname + "\","; //原始名称
65                     jsonM.Data += " \"newname\":\"" + jsonValue.newname + "\","; //新名称
66                     jsonM.Data += " \"path\": \"" + jsonValue.path + "\", ";  //路径
67                     jsonM.Data += " \"thumbpath\":\"" + jsonValue.thumbpath + "\","; //缩略图
68                     jsonM.Data += " \"size\": \"" + jsonValue.size + "\",";   //大小
69                     jsonM.Data += " \"id\": \"" + entity.ID + "\",";   //上传文件ID
70                     jsonM.Data += " \"uptime\": \"" + entity.UPTIME + "\",";   //上传时间
71                     jsonM.Data += " \"operator\": \"" + entity.UPOPEATOR + "\",";   //上传人
72                     jsonM.Data += " \"unitsize\": \"" + entity.UPFILESIZE + unit + "\",";   //带单位大小
73                     jsonM.Data += "\"ext\":\"" + jsonValue.ext + "\"}";//后缀名
74                     #endregion
75                 }
76 
77             }
78             catch (Exception ex)
79             {
80                 jsonM.Msg = "上传过程中发生错误,消息:" + ex.Message;
81                 jsonM.Status = "n";
82             }
83             return Json(jsonM);
84         }

3、4 文件上传方法

 1 /// <summary>
 2        /// 文件上传方法
 3        /// </summary>
 4        /// <param name="postedFile">文件流</param>
 5        /// <param name="isThumbnail">是否生成缩略图</param>
 6        /// <param name="isWater">是否生成水印</param>
 7        /// <returns>上传后文件信息</returns>
 8         private JsonHelper FileSaveAs(HttpPostedFileBase postedFile, bool isThumbnail, bool isWater)
 9         {
10             var jsons = new JsonHelper { Status = "n" };
11             try
12             {
13                 string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.”
14                 int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位
15                 string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名
16                 string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名
17                 string upLoadPath = GetUpLoadPath(fileExt); //上传目录相对路径
18                 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径
19                 string newFilePath = upLoadPath + newFileName; //上传后的路径
20                 string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名
21 
22                 //检查文件扩展名是否合法
23                 if (!CheckFileExt(fileExt))
24                 {
25                     jsons.Msg = "不允许上传" + fileExt + "类型的文件!";
26                     return jsons;
27                 }
28 
29                 //检查文件大小是否合法
30                 if (!CheckFileSize(fileExt, fileSize))
31                 {
32                     jsons.Msg = "文件超过限制的大小啦!";
33                     return jsons;
34                 }
35 
36                 //检查上传的物理路径是否存在,不存在则创建
37                 if (!Directory.Exists(fullUpLoadPath))
38                 {
39                     Directory.CreateDirectory(fullUpLoadPath);
40                 }
41 
42                 //检查文件是否真实合法
43                 //如果文件真实合法 则 保存文件 关闭文件流
44                 //if (!CheckFileTrue(postedFile, fullUpLoadPath + newFileName))
45                 //{
46                 //    jsons.Msg = "不允许上传不可识别的文件!";
47                 //    return jsons;
48                 //}
49 
50                 //保存文件
51                 postedFile.SaveAs(fullUpLoadPath + newFileName);
52 
53                 string thumbnail = string.Empty;
54 
55                 //如果是图片,检查是否需要生成缩略图,是则生成
56                 if (IsImage(fileExt) && isThumbnail && ConfigurationManager.AppSettings["ThumbnailWidth"].ToString() != "0" && ConfigurationManager.AppSettings["ThumbnailHeight"].ToString() != "0")
57                 {
58                     Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName,
59                        int.Parse(ConfigurationManager.AppSettings["ThumbnailWidth"]), int.Parse(ConfigurationManager.AppSettings["ThumbnailHeight"]), "W");
60                     thumbnail = upLoadPath + newThumbnailFileName;
61                 }
62                 //如果是图片,检查是否需要打水印
63                 if (IsImage(fileExt) && isWater)
64                 {
65                     switch (ConfigurationManager.AppSettings["WatermarkType"].ToString())
66                     {
67                         case "1":
68                             WaterMark.AddImageSignText(newFilePath, newFilePath,
69                                 ConfigurationManager.AppSettings["WatermarkText"], int.Parse(ConfigurationManager.AppSettings["WatermarkPosition"]),
70                                 int.Parse(ConfigurationManager.AppSettings["WatermarkImgQuality"]), ConfigurationManager.AppSettings["WatermarkFont"], int.Parse(ConfigurationManager.AppSettings["WatermarkFontsize"]));
71                             break;
72                         case "2":
73                             WaterMark.AddImageSignPic(newFilePath, newFilePath,
74                                 ConfigurationManager.AppSettings["WatermarkPic"], int.Parse(ConfigurationManager.AppSettings["WatermarkPosition"]),
75                                 int.Parse(ConfigurationManager.AppSettings["WatermarkImgQuality"]), int.Parse(ConfigurationManager.AppSettings["WatermarkTransparency"]));
76                             break;
77                     }
78                 }
79 
80                 string unit = string.Empty;
81 
82                 //处理完毕,返回JOSN格式的文件信息
83                 jsons.Data = "{\"oldname\": \"" + fileName + "\",";     //原始文件名
84                 jsons.Data += " \"newname\":\"" + newFileName + "\",";  //文件新名称
85                 jsons.Data += " \"path\": \"" + newFilePath + "\", ";   //文件路径
86                 jsons.Data += " \"thumbpath\":\"" + thumbnail + "\",";  //缩略图路径
87                 jsons.Data += " \"size\": \"" + fileSize + "\",";       //文件大小
88                 jsons.Data += "\"ext\":\"" + fileExt + "\"}";           //文件格式
89                 jsons.Status = "y";
90                 return jsons;
91             }
92             catch
93             {
94                 jsons.Msg = "上传过程中发生意外错误!";
95                 return jsons;
96             }
97         }

3、5 缩略图 水印

  1  /// <summary>
  2     /// 缩略图构造类
  3     /// </summary>
  4     public class Thumbnail
  5     {
  6         private Image srcImage;
  7         private string srcFileName;
  8 
  9         /// <summary>
 10         /// 创建
 11         /// </summary>
 12         /// <param name="FileName">原始图片路径</param>
 13         public bool SetImage(string FileName)
 14         {
 15             srcFileName = Utils.GetMapPath(FileName);
 16             try
 17             {
 18                 srcImage = Image.FromFile(srcFileName);
 19             }
 20             catch
 21             {
 22                 return false;
 23             }
 24             return true;
 25 
 26         }
 27 
 28         /// <summary>
 29         /// 回调
 30         /// </summary>
 31         /// <returns></returns>
 32         public bool ThumbnailCallback()
 33         {
 34             return false;
 35         }
 36 
 37         /// <summary>
 38         /// 生成缩略图,返回缩略图的Image对象
 39         /// </summary>
 40         /// <param name="Width">缩略图宽度</param>
 41         /// <param name="Height">缩略图高度</param>
 42         /// <returns>缩略图的Image对象</returns>
 43         public Image GetImage(int Width, int Height)
 44         {
 45             Image img;
 46             Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
 47             img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
 48             return img;
 49         }
 50 
 51         /// <summary>
 52         /// 保存缩略图
 53         /// </summary>
 54         /// <param name="Width"></param>
 55         /// <param name="Height"></param>
 56         public void SaveThumbnailImage(int Width, int Height)
 57         {
 58             switch (Path.GetExtension(srcFileName).ToLower())
 59             {
 60                 case ".png":
 61                     SaveImage(Width, Height, ImageFormat.Png);
 62                     break;
 63                 case ".gif":
 64                     SaveImage(Width, Height, ImageFormat.Gif);
 65                     break;
 66                 case ".bmp":
 67                     SaveImage(Width, Height, ImageFormat.Bmp);
 68                     break;
 69                 default:
 70                     SaveImage(Width, Height, ImageFormat.Jpeg);
 71                     break;
 72             }
 73         }
 74 
 75         /// <summary>
 76         /// 生成缩略图并保存
 77         /// </summary>
 78         /// <param name="Width">缩略图的宽度</param>
 79         /// <param name="Height">缩略图的高度</param>
 80         /// <param name="imgformat">保存的图像格式</param>
 81         /// <returns>缩略图的Image对象</returns>
 82         public void SaveImage(int Width, int Height, ImageFormat imgformat)
 83         {
 84             if (imgformat != ImageFormat.Gif && (srcImage.Width > Width) || (srcImage.Height > Height))
 85             {
 86                 Image img;
 87                 Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
 88                 img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
 89                 srcImage.Dispose();
 90                 img.Save(srcFileName, imgformat);
 91                 img.Dispose();
 92             }
 93         }
 94 
 95         #region Helper
 96 
 97         /// <summary>
 98         /// 保存图片
 99         /// </summary>
100         /// <param name="image">Image 对象</param>
101         /// <param name="savePath">保存路径</param>
102         /// <param name="ici">指定格式的编解码参数</param>
103         private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
104         {
105             //设置 原图片 对象的 EncoderParameters 对象
106             EncoderParameters parameters = new EncoderParameters(1);
107             parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));
108             image.Save(savePath, ici, parameters);
109             parameters.Dispose();
110         }
111 
112         /// <summary>
113         /// 获取图像编码解码器的所有相关信息
114         /// </summary>
115         /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
116         /// <returns>返回图像编码解码器的所有相关信息</returns>
117         private static ImageCodecInfo GetCodecInfo(string mimeType)
118         {
119             ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
120             foreach (ImageCodecInfo ici in CodecInfo)
121             {
122                 if (ici.MimeType == mimeType)
123                     return ici;
124             }
125             return null;
126         }
127 
128         /// <summary>
129         /// 计算新尺寸
130         /// </summary>
131         /// <param name="width">原始宽度</param>
132         /// <param name="height">原始高度</param>
133         /// <param name="maxWidth">最大新宽度</param>
134         /// <param name="maxHeight">最大新高度</param>
135         /// <returns></returns>
136         private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
137         {
138             //此次2012-02-05修改过=================
139             if (maxWidth <= 0)
140                 maxWidth = width;
141             if (maxHeight <= 0)
142                 maxHeight = height;
143             //以上2012-02-05修改过=================
144             decimal MAX_WIDTH = (decimal)maxWidth;
145             decimal MAX_HEIGHT = (decimal)maxHeight;
146             decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;
147 
148             int newWidth, newHeight;
149             decimal originalWidth = (decimal)width;
150             decimal originalHeight = (decimal)height;
151 
152             if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
153             {
154                 decimal factor;
155                 // determine the largest factor 
156                 if (originalWidth / originalHeight > ASPECT_RATIO)
157                 {
158                     factor = originalWidth / MAX_WIDTH;
159                     newWidth = Convert.ToInt32(originalWidth / factor);
160                     newHeight = Convert.ToInt32(originalHeight / factor);
161                 }
162                 else
163                 {
164                     factor = originalHeight / MAX_HEIGHT;
165                     newWidth = Convert.ToInt32(originalWidth / factor);
166                     newHeight = Convert.ToInt32(originalHeight / factor);
167                 }
168             }
169             else
170             {
171                 newWidth = width;
172                 newHeight = height;
173             }
174             return new Size(newWidth, newHeight);
175         }
176 
177         /// <summary>
178         /// 得到图片格式
179         /// </summary>
180         /// <param name="name">文件名称</param>
181         /// <returns></returns>
182         public static ImageFormat GetFormat(string name)
183         {
184             string ext = name.Substring(name.LastIndexOf(".") + 1);
185             switch (ext.ToLower())
186             {
187                 case "jpg":
188                 case "jpeg":
189                     return ImageFormat.Jpeg;
190                 case "bmp":
191                     return ImageFormat.Bmp;
192                 case "png":
193                     return ImageFormat.Png;
194                 case "gif":
195                     return ImageFormat.Gif;
196                 default:
197                     return ImageFormat.Jpeg;
198             }
199         }
200         #endregion
201 
202         /// <summary>
203         /// 制作小正方形
204         /// </summary>
205         /// <param name="image">图片对象</param>
206         /// <param name="newFileName">新地址</param>
207         /// <param name="newSize">长度或宽度</param>
208         public static void MakeSquareImage(Image image, string newFileName, int newSize)
209         {
210             int i = 0;
211             int width = image.Width;
212             int height = image.Height;
213             if (width > height)
214                 i = height;
215             else
216                 i = width;
217 
218             Bitmap b = new Bitmap(newSize, newSize);
219 
220             try
221             {
222                 Graphics g = Graphics.FromImage(b);
223                 //设置高质量插值法
224                 g.InterpolationMode = InterpolationMode.HighQualityBicubic;
225                 //设置高质量,低速度呈现平滑程度
226                 g.SmoothingMode = SmoothingMode.AntiAlias;
227                 g.PixelOffsetMode = PixelOffsetMode.HighQuality;
228                 //清除整个绘图面并以透明背景色填充
229                 g.Clear(Color.Transparent);
230                 if (width < height)
231                     g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle(0, (height - width) / 2, width, width), GraphicsUnit.Pixel);
232                 else
233                     g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle((width - height) / 2, 0, height, height), GraphicsUnit.Pixel);
234 
235                 SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
236             }
237             finally
238             {
239                 image.Dispose();
240                 b.Dispose();
241             }
242         }
243 
244         /// <summary>
245         /// 制作小正方形
246         /// </summary>
247         /// <param name="fileName">图片文件名</param>
248         /// <param name="newFileName">新地址</param>
249         /// <param name="newSize">长度或宽度</param>
250         public static void MakeSquareImage(string fileName, string newFileName, int newSize)
251         {
252             MakeSquareImage(Image.FromFile(fileName), newFileName, newSize);
253         }
254 
255         /// <summary>
256         /// 制作远程小正方形
257         /// </summary>
258         /// <param name="url">图片url</param>
259         /// <param name="newFileName">新地址</param>
260         /// <param name="newSize">长度或宽度</param>
261         public static void MakeRemoteSquareImage(string url, string newFileName, int newSize)
262         {
263             Stream stream = GetRemoteImage(url);
264             if (stream == null)
265                 return;
266             Image original = Image.FromStream(stream);
267             stream.Close();
268             MakeSquareImage(original, newFileName, newSize);
269         }
270 
271         /// <summary>
272         /// 制作缩略图
273         /// </summary>
274         /// <param name="original">图片对象</param>
275         /// <param name="newFileName">新图路径</param>
276         /// <param name="maxWidth">最大宽度</param>
277         /// <param name="maxHeight">最大高度</param>
278         public static void MakeThumbnailImage(Image original, string newFileName, int maxWidth, int maxHeight)
279         {
280             Size _newSize = ResizeImage(original.Width, original.Height, maxWidth, maxHeight);
281 
282             using (Image displayImage = new Bitmap(original, _newSize))
283             {
284                 try
285                 {
286                     if (original.Width > maxWidth)
287                     {
288                         displayImage.Save(newFileName, original.RawFormat);
289                     }
290                 }
291                 finally
292                 {
293                     original.Dispose();
294                 }
295             }
296         }
297 
298         /// <summary>
299         /// 制作缩略图
300         /// </summary>
301         /// <param name="fileName">文件名</param>
302         /// <param name="newFileName">新图路径</param>
303         /// <param name="maxWidth">最大宽度</param>
304         /// <param name="maxHeight">最大高度</param>
305         public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight)
306         {
307             //2012-02-05修改过,支持替换
308             byte[] imageBytes = File.ReadAllBytes(fileName);
309             Image img = Image.FromStream(new System.IO.MemoryStream(imageBytes));
310             if (img.Width > maxWidth)
311             {
312                 MakeThumbnailImage(img, newFileName, maxWidth, maxHeight);
313             }
314             //原文
315             //MakeThumbnailImage(Image.FromFile(fileName), newFileName, maxWidth, maxHeight);
316         }
317 
318         #region 2012-2-19 新增生成图片缩略图方法
319         /// <summary>
320         /// 生成缩略图
321         /// </summary>
322         /// <param name="fileName">源图路径(绝对路径)</param>
323         /// <param name="newFileName">缩略图路径(绝对路径)</param>
324         /// <param name="width">缩略图宽度</param>
325         /// <param name="height">缩略图高度</param>
326         /// <param name="mode">生成缩略图的方式</param>    
327         public static bool MakeThumbnailImage(string fileName, string newFileName, int width, int height, string mode)
328         {
329             Image originalImage = Image.FromFile(fileName);
330             int towidth = width;
331             int toheight = height;
332 
333             int x = 0;
334             int y = 0;
335             int ow = originalImage.Width;
336             int oh = originalImage.Height;
337 
338             if (ow > towidth)
339             {
340                 switch (mode)
341                 {
342                     case "HW"://指定高宽缩放(可能变形)                
343                         break;
344                     case "W"://指定宽,高按比例                    
345                         toheight = originalImage.Height * width / originalImage.Width;
346                         break;
347                     case "H"://指定高,宽按比例
348                         towidth = originalImage.Width * height / originalImage.Height;
349                         break;
350                     case "Cut"://指定高宽裁减(不变形)                
351                         if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
352                         {
353                             oh = originalImage.Height;
354                             ow = originalImage.Height * towidth / toheight;
355                             y = 0;
356                             x = (originalImage.Width - ow) / 2;
357                         }
358                         else
359                         {
360                             ow = originalImage.Width;
361                             oh = originalImage.Width * height / towidth;
362                             x = 0;
363                             y = (originalImage.Height - oh) / 2;
364                         }
365                         break;
366                     default:
367                         break;
368                 }
369 
370                 //新建一个bmp图片
371                 Bitmap b = new Bitmap(towidth, toheight);
372                 try
373                 {
374                     //新建一个画板
375                     Graphics g = Graphics.FromImage(b);
376                     //设置高质量插值法
377                     g.InterpolationMode = InterpolationMode.HighQualityBicubic;
378                     //设置高质量,低速度呈现平滑程度
379                     g.SmoothingMode = SmoothingMode.AntiAlias;
380                     g.PixelOffsetMode = PixelOffsetMode.HighQuality;
381                     //清空画布并以透明背景色填充
382                     g.Clear(Color.Transparent);
383                     //在指定位置并且按指定大小绘制原图片的指定部分
384                     g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
385 
386                     SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
387                 }
388                 catch (System.Exception e)
389                 {
390                     throw e;
391                 }
392                 finally
393                 {
394                     originalImage.Dispose();
395                     b.Dispose();
396                 }
397                 return true;
398             }
399             else
400             {
401                 originalImage.Dispose();
402                 return false;
403             }
404         }
405         #endregion
406 
407         #region 2012-10-30 新增图片裁剪方法
408         /// <summary>
409         /// 裁剪图片并保存
410         /// </summary>
411         /// <param name="fileName">源图路径(绝对路径)</param>
412         /// <param name="newFileName">缩略图路径(绝对路径)</param>
413         /// <param name="maxWidth">缩略图宽度</param>
414         /// <param name="maxHeight">缩略图高度</param>
415         /// <param name="cropWidth">裁剪宽度</param>
416         /// <param name="cropHeight">裁剪高度</param>
417         /// <param name="X">X轴</param>
418         /// <param name="Y">Y轴</param>
419         public static bool MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y)
420         {
421             byte[] imageBytes = File.ReadAllBytes(fileName);
422             Image originalImage = Image.FromStream(new System.IO.MemoryStream(imageBytes));
423             Bitmap b = new Bitmap(cropWidth, cropHeight);
424             try
425             {
426                 using (Graphics g = Graphics.FromImage(b))
427                 {
428                     //设置高质量插值法
429                     g.InterpolationMode = InterpolationMode.HighQualityBicubic;
430                     //设置高质量,低速度呈现平滑程度
431                     g.SmoothingMode = SmoothingMode.AntiAlias;
432                     g.PixelOffsetMode = PixelOffsetMode.HighQuality;
433                     //清空画布并以透明背景色填充
434                     g.Clear(Color.Transparent);
435                     //在指定位置并且按指定大小绘制原图片的指定部分
436                     g.DrawImage(originalImage, new Rectangle(0, 0, cropWidth, cropWidth), X, Y, cropWidth, cropHeight, GraphicsUnit.Pixel);
437                     Image displayImage = new Bitmap(b, maxWidth, maxHeight);
438                     SaveImage(displayImage, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
439                     return true;
440                 }
441             }
442             catch (System.Exception e)
443             {
444                 throw e;
445             }
446             finally
447             {
448                 originalImage.Dispose();
449                 b.Dispose();
450             }
451         }
452         #endregion
453 
454         /// <summary>
455         /// 制作远程缩略图
456         /// </summary>
457         /// <param name="url">图片URL</param>
458         /// <param name="newFileName">新图路径</param>
459         /// <param name="maxWidth">最大宽度</param>
460         /// <param name="maxHeight">最大高度</param>
461         public static void MakeRemoteThumbnailImage(string url, string newFileName, int maxWidth, int maxHeight)
462         {
463             Stream stream = GetRemoteImage(url);
464             if (stream == null)
465                 return;
466             Image original = Image.FromStream(stream);
467             stream.Close();
468             MakeThumbnailImage(original, newFileName, maxWidth, maxHeight);
469         }
470 
471         /// <summary>
472         /// 获取图片流
473         /// </summary>
474         /// <param name="url">图片URL</param>
475         /// <returns></returns>
476         private static Stream GetRemoteImage(string url)
477         {
478             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
479             request.Method = "GET";
480             request.ContentLength = 0;
481             request.Timeout = 20000;
482             HttpWebResponse response = null;
483 
484             try
485             {
486                 response = (HttpWebResponse)request.GetResponse();
487                 return response.GetResponseStream();
488             }
489             catch
490             {
491                 return null;
492             }
493         }
494     }
495     /// <summary>
496     /// 水印构造类
497     /// </summary>
498     public class WaterMark
499     {
500         /// <summary>
501         /// 图片水印
502         /// </summary>
503         /// <param name="imgPath">服务器图片相对路径</param>
504         /// <param name="filename">保存文件名</param>
505         /// <param name="watermarkFilename">水印文件相对路径</param>
506         /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
507         /// <param name="quality">附加水印图片质量,0-100</param>
508         /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
509         public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
510         {
511             if (!File.Exists(Utils.GetMapPath(imgPath)))
512                 return;
513             byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
514             Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
515             filename = Utils.GetMapPath(filename);
516 
517             if (watermarkFilename.StartsWith("/") == false)
518                 watermarkFilename = "/" + watermarkFilename;
519             watermarkFilename = Utils.GetMapPath(watermarkFilename);
520             if (!File.Exists(watermarkFilename))
521                 return;
522             Graphics g = Graphics.FromImage(img);
523             //设置高质量插值法
524             //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
525             //设置高质量,低速度呈现平滑程度
526             //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
527             Image watermark = new Bitmap(watermarkFilename);
528 
529             if (watermark.Height >= img.Height || watermark.Width >= img.Width)
530                 return;
531 
532             ImageAttributes imageAttributes = new ImageAttributes();
533             ColorMap colorMap = new ColorMap();
534 
535             colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
536             colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
537             ColorMap[] remapTable = { colorMap };
538 
539             imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
540 
541             float transparency = 0.5F;
542             if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
543                 transparency = (watermarkTransparency / 10.0F);
544 
545 
546             float[][] colorMatrixElements = {
547                                                 new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
548                                                 new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
549                                                 new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
550                                                 new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
551                                                 new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
552                                             };
553 
554             ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
555 
556             imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
557 
558             int xpos = 0;
559             int ypos = 0;
560 
561             switch (watermarkStatus)
562             {
563                 case 1:
564                     xpos = (int)(img.Width * (float).01);
565                     ypos = (int)(img.Height * (float).01);
566                     break;
567                 case 2:
568                     xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
569                     ypos = (int)(img.Height * (float).01);
570                     break;
571                 case 3:
572                     xpos = (int)((img.Width * (float).99) - (watermark.Width));
573                     ypos = (int)(img.Height * (float).01);
574                     break;
575                 case 4:
576                     xpos = (int)(img.Width * (float).01);
577                     ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
578                     break;
579                 case 5:
580                     xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
581                     ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
582                     break;
583                 case 6:
584                     xpos = (int)((img.Width * (float).99) - (watermark.Width));
585                     ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
586                     break;
587                 case 7:
588                     xpos = (int)(img.Width * (float).01);
589                     ypos = (int)((img.Height * (float).99) - watermark.Height);
590                     break;
591                 case 8:
592                     xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
593                     ypos = (int)((img.Height * (float).99) - watermark.Height);
594                     break;
595                 case 9:
596                     xpos = (int)((img.Width * (float).99) - (watermark.Width));
597                     ypos = (int)((img.Height * (float).99) - watermark.Height);
598                     break;
599             }
600 
601             g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
602 
603             ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
604             ImageCodecInfo ici = null;
605             foreach (ImageCodecInfo codec in codecs)
606             {
607                 if (codec.MimeType.IndexOf("jpeg") > -1)
608                     ici = codec;
609             }
610             EncoderParameters encoderParams = new EncoderParameters();
611             long[] qualityParam = new long[1];
612             if (quality < 0 || quality > 100)
613                 quality = 80;
614 
615             qualityParam[0] = quality;
616 
617             EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
618             encoderParams.Param[0] = encoderParam;
619 
620             if (ici != null)
621                 img.Save(filename, ici, encoderParams);
622             else
623                 img.Save(filename);
624 
625             g.Dispose();
626             img.Dispose();
627             watermark.Dispose();
628             imageAttributes.Dispose();
629         }
630 
631         /// <summary>
632         /// 文字水印
633         /// </summary>
634         /// <param name="imgPath">服务器图片相对路径</param>
635         /// <param name="filename">保存文件名</param>
636         /// <param name="watermarkText">水印文字</param>
637         /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
638         /// <param name="quality">附加水印图片质量,0-100</param>
639         /// <param name="fontname">字体</param>
640         /// <param name="fontsize">字体大小</param>
641         public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
642         {
643             byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
644             Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
645             filename = Utils.GetMapPath(filename);
646 
647             Graphics g = Graphics.FromImage(img);
648             Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
649             SizeF crSize;
650             crSize = g.MeasureString(watermarkText, drawFont);
651 
652             float xpos = 0;
653             float ypos = 0;
654 
655             switch (watermarkStatus)
656             {
657                 case 1:
658                     xpos = (float)img.Width * (float).01;
659                     ypos = (float)img.Height * (float).01;
660                     break;
661                 case 2:
662                     xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
663                     ypos = (float)img.Height * (float).01;
664                     break;
665                 case 3:
666                     xpos = ((float)img.Width * (float).99) - crSize.Width;
667                     ypos = (float)img.Height * (float).01;
668                     break;
669                 case 4:
670                     xpos = (float)img.Width * (float).01;
671                     ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
672                     break;
673                 case 5:
674                     xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
675                     ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
676                     break;
677                 case 6:
678                     xpos = ((float)img.Width * (float).99) - crSize.Width;
679                     ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
680                     break;
681                 case 7:
682                     xpos = (float)img.Width * (float).01;
683                     ypos = ((float)img.Height * (float).99) - crSize.Height;
684                     break;
685                 case 8:
686                     xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
687                     ypos = ((float)img.Height * (float).99) - crSize.Height;
688                     break;
689                 case 9:
690                     xpos = ((float)img.Width * (float).99) - crSize.Width;
691                     ypos = ((float)img.Height * (float).99) - crSize.Height;
692                     break;
693             }
694 
695             g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
696             g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Yellow), xpos, ypos);
697 
698             ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
699             ImageCodecInfo ici = null;
700             foreach (ImageCodecInfo codec in codecs)
701             {
702                 if (codec.MimeType.IndexOf("jpeg") > -1)
703                     ici = codec;
704             }
705             EncoderParameters encoderParams = new EncoderParameters();
706             long[] qualityParam = new long[1];
707             if (quality < 0 || quality > 100)
708                 quality = 80;
709 
710             qualityParam[0] = quality;
711 
712             EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
713             encoderParams.Param[0] = encoderParam;
714 
715             if (ici != null)
716                 img.Save(filename, ici, encoderParams);
717             else
718                 img.Save(filename);
719 
720             g.Dispose();
721             img.Dispose();
722         }
723     }

3、6 通过路径获取文件方法

 1 /// <summary>
 2         /// 通过路径获取文件
 3         /// </summary>
 4         /// <returns></returns>
 5         public ActionResult GetFileData()
 6         {
 7             string path = Request.Form["path"];
 8             var jsonM = new JsonHelper() { Status = "y", Msg = "success" };
 9             try
10             {
11                 if (!FileHelper.IsExistDirectory(Server.MapPath(path)))
12                 {
13                     jsonM.Status = "n";
14                     jsonM.Msg = "目录不存在!";
15                 }
16                 else if (FileHelper.IsEmptyDirectory(Server.MapPath(path)))
17                 {
18                     jsonM.Status = "empty";
19                 }
20                 else
21                 {
22                     jsonM.Data = Common.Utils.DataTableToList<FileModel>(FileHelper.GetFileTable(Server.MapPath(path))).OrderByDescending(p => p.name).ToList();
23                 }
24             }
25             catch (Exception)
26             {
27                 jsonM.Status = "err";
28                 jsonM.Msg = "获取文件失败!";
29             }
30             return Content(JsonConverter.Serialize(jsonM, true));
31         }

3.8 FileHelper中的获取文件的方法

 1  /// <summary>
 2         /// 读取指定位置文件列表到集合中
 3         /// </summary>
 4         /// <param name="Path">指定路径</param>
 5         /// <returns></returns>
 6         public static DataTable GetFileTable(string Path)
 7         {
 8             DataTable dt = new DataTable();
 9             dt.Columns.Add("name", typeof(string));
10             dt.Columns.Add("ext", typeof(string));
11             dt.Columns.Add("size", typeof(string));
12             dt.Columns.Add("icon", typeof(string));
13             dt.Columns.Add("isfolder", typeof(bool));
14             dt.Columns.Add("isImage", typeof(bool));
15             dt.Columns.Add("fullname", typeof(string));
16             dt.Columns.Add("path", typeof(string));
17             dt.Columns.Add("time", typeof(DateTime));
18 
19             DirectoryInfo dirinfo = new DirectoryInfo(Path);
20             FileInfo fi;
21             DirectoryInfo dir;
22             string FileName = string.Empty, FileExt = string.Empty, FileSize = string.Empty, FileIcon = string.Empty, FileFullName = string.Empty, FilePath = string.Empty;
23             bool IsFloder = false, IsImage = false;
24             DateTime FileModify;
25             try
26             {
27                 foreach (FileSystemInfo fsi in dirinfo.GetFileSystemInfos())
28                 {
29                     if (fsi is FileInfo)
30                     {
31                         fi = (FileInfo)fsi;
32                         //获取文件名称
33                         FileName = fi.Name.Substring(0, fi.Name.LastIndexOf('.'));
34                         FileFullName = fi.Name;
35                         //获取文件扩展名
36                         FileExt = fi.Extension;
37                         //获取文件大小
38                         FileSize = GetDiyFileSize(fi);
39                         //获取文件最后修改时间
40                         FileModify = fi.LastWriteTime;
41                         //文件图标
42                         FileIcon = GetFileIcon(FileExt);
43                         //是否为图片
44                         IsImage = IsImageFile(FileExt.Substring(1, FileExt.Length - 1));
45                         //文件路径
46                         FilePath = urlconvertor(fi.FullName);
47                     }
48                     else
49                     {
50                         dir = (DirectoryInfo)fsi;
51                         //获取目录名
52                         FileName = dir.Name;
53                         //获取目录最后修改时间
54                         FileModify = dir.LastWriteTime;
55                         //设置目录文件为文件夹
56                         FileExt = "folder";
57                         //文件夹图标
58                         FileIcon = "fa fa-folder";
59                         IsFloder = true;
60                         //文件路径
61                         FilePath = urlconvertor(dir.FullName);
62 
63                     }
64                     DataRow dr = dt.NewRow();
65                     dr["name"] = FileName;
66                     dr["fullname"] = FileFullName;
67                     dr["ext"] = FileExt;
68                     dr["size"] = FileSize;
69                     dr["time"] = FileModify;
70                     dr["icon"] = FileIcon;
71                     dr["isfolder"] = IsFloder;
72                     dr["isImage"] = IsImage;
73                     dr["path"] = FilePath;
74                     dt.Rows.Add(dr);
75                 }
76             }
77             catch (Exception e)
78             {
79 
80                 throw e;
81             }
82             return dt;
83         }

 

 

原创文章 转载请尊重劳动成果 http://yuangang.cnblogs.com

posted @ 2016-06-30 13:20  果冻布丁喜之郎  阅读(56439)  评论(41编辑  收藏  举报