學習ASP.NET Core Razor 編程系列目錄
學習ASP.NET Core Razor 編程系列二——添加一個實體
學習ASP.NET Core Razor 編程系列三——創建數據表及創建項目基本頁面
學習ASP.NET Core Razor 編程系列四——Asp.Net Core Razor列表模板頁面
學習ASP.NET Core Razor 編程系列五——Asp.Net Core Razor新建模板頁面
學習ASP.NET Core Razor 編程系列六——數據庫初始化
學習ASP.NET Core Razor 編程系列七——修改列表頁面
學習ASP.NET Core Razor 編程系列八——並發處理
學習ASP.NET Core Razor 編程系列九——增加查詢功能
學習ASP.NET Core Razor 編程系列十——添加新字段
學習ASP.NET Core Razor 編程系列十一——把新字段更新到數據庫
學習ASP.NET Core Razor 編程系列十二——在頁面中增加校驗
本篇文章我們來講在書籍信息管理系統示例使用簡單的模型綁定上傳文件,本文的示例適合上傳小型文件。本篇文章演示如何通過單個 POST 將兩個文件上傳至服務器。
安全注意事項
在向用戶提供向上傳文件的功能時,必須格外注意安全性。 攻擊者可能對系統執行拒絕服務和其他攻擊。 所以在提供上傳功能時需要注意以下安全措施:
1. 將文件上傳到系統上的專用文件上傳目錄,這樣可以更輕松地對上傳內容實施安全措施。如果允許文件上傳,請確保在上傳目錄禁用執行權限。
2. 上傳文件的文件名在服務器端保存時要由應用程序自動重新命名文件名稱,而不是采用用戶輸入或已上傳文件的文件名。
3. 僅允許使用一組特定的文件擴展名。
4. 在服務端重新執行客戶端檢查。 不要相信客戶端檢查,因為客戶端檢查很容易規避。
5. 檢查上傳文件大小,防止上傳文件的大小比預期的文件大小大。
6. 對上傳文件的內容進行病毒/惡意軟件掃描程序。
警告
將惡意代碼上傳到系統通常是執行代碼的第一步,這些代碼可以實現以下功能:
1. 完全接管系統。
2. 重載系統,導致系統完全崩潰。
3. 泄露用戶或系統數據。
一、添加類FileUpload
在Visual Studio 2017的解決方案資源管理器中,鼠標左鍵選中“Models”文件夾,右鍵單擊,在彈出菜單中選擇“添加—>類”(如下圖)。 將類命名為“FileUpload”,並添加以下代碼,代碼如下:
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace RazorMvcBooks.Models { public class FileUpload { [Required] [Display(Name = "文件名")] [StringLength(60, MinimumLength = 3)] public string FileName { get; set; } [Required] [Display(Name = "公共描述")] public IFormFile UploadPublicDescribe { get; set; } [Required] [Display(Name = "后台描述")] public IFormFile UploadPrivateDescribe { get; set; } } }
此類有一個屬性對應文件名稱,另各有一個屬性對應相應的上傳文件。 3 個屬性皆為必需屬性,文件名長度必須為 3-60 個字符。 FileUpload 類與頁面綁定以獲取上傳文件數據。
二、添加一個用於上傳文件的文件輔助類FileHelpers
為避免處理上傳文件文件時出現重復代碼,我們首先創建一個靜態文件用於處理上傳功能。
在Visual Studio 2017 的解決方案資源管理器中創建一個“Utils”文件夾,然后此文件夾下創建一個“FileHelpers.cs”類文件,並添加以下內容。方法 ProcessFormFile 接受 IFormFile 和 ModelStateDictionary,並返回包含文件大小和內容的字符串。 檢查內容類型和長度。 如果上傳文件未通過校驗,將向 ModelState 添加一個錯誤。
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; using RazorMvcBooks.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace RazorMvcBooks.Utils { public class FileHelpers { public static async Task<string> ProcessFormFile(IFormFile formFile, ModelStateDictionary modelState) { var fieldDisplayName = string.Empty; // 使用反射獲得的IFormFile實例對象的文件名稱。 // 如果名稱沒有找到,將會有一個簡單的錯誤消息,但不會顯示文件名稱 MemberInfo property = typeof(FileUpload).GetProperty(formFile.Name.Substring(formFile.Name.IndexOf(".") + 1)); if (property != null) { var displayAttribute = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute; if (displayAttribute != null) { fieldDisplayName = $"{displayAttribute.Name} "; } } //使用path.GetFileName獲取一個帶路徑的全文件名。 //通過HtmlEncode進行編碼的結果必須在錯誤消息中返回。 var fileName = WebUtility.HtmlEncode(Path.GetFileName(formFile.FileName)); if (formFile.ContentType.ToLower() != "text/plain") { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) must be a text file."); } //校驗文件長度,如果文件不包含內容,則不必讀取文件長度。 //此校驗不會檢查僅具有BOM(字節順序標記)作為內容的文件, //因此在讀取文件內容后再次檢驗文件內容長度,以校驗僅包含BOM的文件。 if (formFile.Length == 0) { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) is empty."); } else if (formFile.Length > 1048576) { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) exceeds 1 MB."); } else { try { string fileContents; //使用StreamReader按UTF-8編碼讀取文件。 //如果上傳文件是采用其他的編碼。 //請使用32位編碼,將UTF8Encoding改為UTF32Encoding using ( var reader = new StreamReader( formFile.OpenReadStream(), new UTF32Encoding(), detectEncodingFromByteOrderMarks: true)) { fileContents = await reader.ReadToEndAsync(); // 檢查文件長度,如果文件的唯一內容是BOM,在刪除BOM后內容實際上是空的。 if (fileContents.Length > 0) { return fileContents; } else { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) is empty."); } } } catch (Exception ex) { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) upload failed. " + $"Please contact the Help Desk for support. Error: {ex.Message}"); // Log the exception } } return string.Empty; } } }
三、添加Describe類
在Visual Studio 2017的解決方案資源管理器中,鼠標左鍵選中“Models”文件夾,右鍵單擊,在彈出菜單中選擇“添加—>類”(如下圖)。 將類命名為“Describe”,並添加以下屬性,代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace RazorMvcBooks.Models { public class Describe { public int ID { get; set; } [Display(Name = "文件名稱")] public string Name { get; set; } [Display(Name = "公共描述")] public string PublicDescribe { get; set; } [Display(Name = "公共描述大小(bytes)")] [DisplayFormat(DataFormatString = "{0:N1}")] public long PublicScheduleSize { get; set; } [Display(Name = "后台描述")] public string PrivateDescribe { get; set; } [Display(Name = "后台描述大小 (bytes)")] [DisplayFormat(DataFormatString = "{0:N1}")] public long PrivateScheduleSize { get; set; } [Display(Name = "上傳時間(UTC)")] [DisplayFormat(DataFormatString = "{0:F}")] public DateTime UploadDateTime { get; set; } } }
此類使用 Display 和 DisplayFormat 特性,有前端顯示時,這些特性會生成友好的標題和格式。
四、修改BookContext
在Visual Studio 2017中打開BookContext (Models/BookContext.cs) 文件,並修改代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace RazorMvcBooks.Models { public class BookContext:DbContext { public BookContext(DbContextOptions<BookContext> options) : base(options) { } public DbSet<Book> Book { get; set; } public DbSet<Describe> Describe { get; set; } } }
五、將 “描述信息” 表添加到數據庫
在Visual Studio 2017中打開包管理器控制台 (PMC):“工具” > “NuGet 包管理器” > “包管理器控制台”。
在 PMC 中執行以下命令。 這些命令將向數據庫添加 Describe 表,執行結果發下圖:
Add-Migration AddDescribeTable
Update-Database
在執行以上指令之后,會在數據庫中添加Describe表,結果如下圖。