標籤:
寫在前面
上篇文章修改檔案上傳的邏輯,這篇修改下檔案下載的邏輯。
系列文章
[EF]vs15+ef6+mysql code first方式
[實戰]MVC5+EF6+MySql企業網盤實戰(1)
[實戰]MVC5+EF6+MySql企業網盤實戰(2)——使用者註冊
[實戰]MVC5+EF6+MySql企業網盤實戰(3)——驗證碼
[實戰]MVC5+EF6+MySql企業網盤實戰(4)——上傳頭像
[Bootstrap]modal彈出框
[實戰]MVC5+EF6+MySql企業網盤實戰(5)——登入介面,頭像等比例壓縮
[實戰]MVC5+EF6+MySql企業網盤實戰(5)——頁面模板
[實戰]MVC5+EF6+MySql企業網盤實戰(5)——ajax方式註冊
[實戰]MVC5+EF6+MySql企業網盤實戰(6)——ajax方式登入
[實戰]MVC5+EF6+MySql企業網盤實戰(7)——檔案上傳
[實戰]MVC5+EF6+MySql企業網盤實戰(8)——檔案下載、刪除
[實戰]MVC5+EF6+MySql企業網盤實戰(9)——編輯檔案名稱
[實戰]MVC5+EF6+MySql企業網盤實戰(10)——建立檔案夾
[實戰]MVC5+EF6+MySql企業網盤實戰(11)——建立檔案夾2
[實戰]MVC5+EF6+MySql企業網盤實戰(12)——建立檔案夾和上傳檔案
[實戰]MVC5+EF6+MySql企業網盤實戰(13)——編輯檔案夾
[實戰]MVC5+EF6+MySql企業網盤實戰(14)——邏輯重構
[實戰]MVC5+EF6+MySql企業網盤實戰(15)——邏輯重構2
檔案下載
下載傳入的參數不變,但是這個時候需要根據檔案的md5,去目錄NetDisk中尋找檔案。這樣才能真正的找到物理檔案。
代碼如下:
/// <summary> /// 檔案下載 /// </summary> /// <param name="fileId"></param> public void DownLoadFile(string fileId) { UserInfo userInfo = Session["user"] as UserInfo; if (userInfo == null) { RedirectToAction("Login", "UserInfo"); return; } if (string.IsNullOrEmpty(fileId)) { throw new ArgumentNullException("fileId is errror"); } int id = Convert.ToInt32(fileId); var findFile = _myFileServiceRepository.Find(x => x.Id == id); if (findFile == null) { AlertMsg("檔案不存在", ""); return; } string filePath = Path.Combine(Server.MapPath("~/NetDisk/"), findFile.FileMd5 + findFile.FileExt); //以字元流的形式下載檔案 FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通知瀏覽器下載檔案而不是開啟 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(findFile.FileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }總結
下載的邏輯也很好修改,只是修改一下檔案的路徑,在資料庫中已經存有md5和檔案的副檔名,這時候拼接一個檔案的真實路徑就可以了。
[實戰]MVC5+EF6+MySql企業網盤實戰(15)——邏輯重構2