檔案上傳前驗證是系統安全的第一道防線。雖然前端可攔截,但後端驗證不可省略 (前端可繞過)。本文提供可配置、可重用的後端驗證邏輯。
using System.Configuration;
using System.IO;
public static class UploadValidator
{
/// 驗證檔案副檔名是否在允許清單中
public static bool IsAllowedExtension(string fileName)
{
if (string.IsNullOrEmpty(fileName)) return false;
string ext = Path.GetExtension(fileName).ToLowerInvariant();
string allowedExts = ConfigurationManager.AppSettings["AllowedExtensions"] ?? ".jpg|.jpeg|.png|.gif|.bmp";
return allowedExts.Split('|').Contains(ext);
}
/// 驗證檔案大小是否超過限制
public static bool IsAllowedSize(long contentLength)
{
string maxSizeStr = ConfigurationManager.AppSettings["MaxUploadSizeKB"] ?? "2048"; // 預設 2MB
if (!int.TryParse(maxSizeStr, out int maxKB)) maxKB = 2048;
long maxBytes = maxKB * 1024L;
return contentLength > 0 && contentLength <= maxBytes;
}
/// 綜合驗證 (回傳錯誤訊息,null 表示通過)
public static string Validate(HttpPostedFile file)
{
if (file == null || file.ContentLength == 0)
return "請選擇要上傳的檔案";
if (!IsAllowedExtension(file.FileName))
return $"檔案格式不允許。允許格式:{ConfigurationManager.AppSettings["AllowedExtensions"]?.Replace("|", ", ")}";
if (!IsAllowedSize(file.ContentLength))
return $"檔案大小超過限制 (最大 {ConfigurationManager.AppSettings["MaxUploadSizeKB"]} KB)";
// 進階:驗證 Magic Number (檔案真實內容) - 防止偽裝副檔名
if (!ValidateMagicNumber(file.InputStream))
return "檔案內容與副檔名不符,可能為偽裝檔案";
return null; // 通過驗證
}
/// 驗證檔案簽名
private static bool ValidateMagicNumber(Stream stream)
{
// 常見圖片 Magic Numbers
var signatures = new Dictionary
{
[".jpg"] = new[] { new byte[] { 0xFF, 0xD8, 0xFF } },
[".png"] = new[] { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A } },
[".gif"] = new[] { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 } },
[".bmp"] = new[] { new byte[] { 0x42, 0x4D } }
};
string ext = Path.GetExtension(stream.GetType().Name).ToLower(); // 注意:這裡需從檔名取得副檔名
// 實際應用中應從 HttpPostedFile.FileName 取得副檔名
if (!signatures.TryGetValue(ext, out var sigs)) return true; // 未定義簽名則跳過
byte[] header = new byte[8];
stream.Position = 0;
stream.Read(header, 0, header.Length);
stream.Position = 0;
return sigs.Any(sig => header.Take(sig.Length).SequenceEqual(sig));
}
}
<appSettings>
<!-- 允許副檔名,以 | 分隔,全部小寫 -->
<add key="AllowedExtensions" value=".jpg|.jpeg|.png|.gif|.bmp|.pdf|.doc|.docx|.xls|.xlsx" />
<!-- 最大上傳大小 (KB) -->
<add key="MaxUploadSizeKB" value="5120" /> <!-- 5MB -->
</appSettings>
<!-- IIS 要求大小限制 (需同步設定,否則大檔案直接被 IIS 擋下) -->
<system.web>
<httpRuntime maxRequestLength="5120" executionTimeout="300" /> <!-- KB, 秒 -->
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="5242880" /> <!-- Bytes (5MB) -->
</requestFiltering>
</security>
</system.webServer>
// Web Forms
protected void btnUpload_Click(object sender, EventArgs e)
{
string error = UploadValidator.Validate(fuFile.PostedFile);
if (error != null) { lblMsg.Text = error; return; }
// 通過驗證,進行儲存邏輯...
}
// MVC Controller
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
string error = UploadValidator.Validate(file);
if (error != null) return Json(new { success = false, message = error });
// 儲存邏輯...
return Json(new { success = true, path = savedPath });
}
IFormFile 介面,驗證邏輯封裝為 IFormFileValidator 服務,注入 Controller。嚴謹的上傳驗證是防止惡意檔案上傳、遠端代碼執行 (RCE) 攻擊的關鍵,請務必在每個上傳入口點統一套用。