【無私分享:從入門到精通ASP.NET MVC】從0開始,一起搭框架、做專案 (11)檔案管理
阿新 • • 發佈:2019-01-18
索引
簡述
檔案管理,這個比較雞肋 但是有些方法 大家可以參考下
專案準備
我們用的工具是: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> 沒有找到任何檔案</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