FileUpload.PostedFile.ContentLength 即時攔截超大檔案httpRuntime maxRequestLength 防止惡意繞過前端上傳超大請求<%@ Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>檔案上傳大小限制示範</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>選擇要上傳的檔案 (限制 2MB):</h4>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="UploadButton" Text="上傳檔案" OnClick="UploadButton_Click" runat="server" />
<hr />
<asp:Label ID="UploadStatusLabel" runat="server" ForeColor="Green" />
</div>
</form>
</body>
</html>
<script runat="server">
protected void UploadButton_Click(object sender, EventArgs e) {
string savePath = @"C:\Temp\Uploads\"; // 確保目錄存在且 IIS_IUSRS 有寫入權限
if (FileUpload1.HasFile) {
int fileSize = FileUpload1.PostedFile.ContentLength; // 位元組
// 前端邏輯限制:2MB = 2,097,152 bytes (範例用 2,100,000)
const int MAX_SIZE = 2_100_000;
if (fileSize < MAX_SIZE) {
try {
string fileName = Server.HtmlEncode(FileUpload1.FileName); // 防 XSS
string fullPath = System.IO.Path.Combine(savePath, fileName);
FileUpload1.SaveAs(fullPath);
UploadStatusLabel.Text = $"檔案 {fileName} 上傳成功!大小:{fileSize:N0} bytes";
UploadStatusLabel.ForeColor = System.Drawing.Color.Green;
} catch (Exception ex) {
UploadStatusLabel.Text = "儲存失敗:" + ex.Message;
UploadStatusLabel.ForeColor = System.Drawing.Color.Red;
}
} else {
UploadStatusLabel.Text = $"檔案過大 ({fileSize:N0} bytes),限制 {MAX_SIZE:N0} bytes (約 2MB)";
UploadStatusLabel.ForeColor = System.Drawing.Color.Red;
}
} else {
UploadStatusLabel.Text = "請先選擇檔案";
UploadStatusLabel.ForeColor = System.Drawing.Color.Orange;
}
}
</script>
<configuration>
<system.web>
<!-- maxRequestLength 單位為 KB,executionTimeout 單位為秒 -->
<httpRuntime maxRequestLength="2048" executionTimeout="120" /> <!-- 限制 2MB -->
</system.web>
<!-- IIS 7+ 整合管道模式需額外設定 -->
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength 單位為 Bytes -->
<requestLimits maxAllowedContentLength="2097152" /> <!-- 2MB = 2*1024*1024 -->
</requestFiltering>
</security>
</system.webServer>
</configuration>
| 設定 | 位置 | 單位 | 作用範圍 | IIS 版本 |
|---|---|---|---|---|
| maxRequestLength | system.web/httpRuntime | KB | ASP.NET 管道 | 所有版本 |
| maxAllowedContentLength | system.webServer/security/requestFiltering/requestLimits | Bytes | IIS 核心 (早於 ASP.NET) | IIS 7.0+ |
maxAllowedContentLength (IIS 7+)HttpException,需在 Global.asax Application_Error 捕獲並友善提示Path.GetFileName 取純檔名,Server.HtmlEncode 防 XSS,儲存時建議重新命名 (GUID + 原副檔名)FileUpload 會將整個檔案讀入記憶體。超過 10MB 建議改用分塊上傳、Plupload、FineUploader 或 ASP.NET Core 的 IFormFile 流式處理public class ValidatedFileUpload : FileUpload {
public int MaxFileSizeKB { get; set; } = 2048;
public string[] AllowedExtensions { get; set; } = { ".jpg", ".png", ".pdf", ".docx" };
public bool ValidateFile(out string errorMessage) {
errorMessage = "";
if (!HasFile) { errorMessage = "未選擇檔案"; return false; }
if (PostedFile.ContentLength > MaxFileSizeKB * 1024) { errorMessage = $"超過 {MaxFileSizeKB}KB 限制"; return false; }
string ext = System.IO.Path.GetExtension(FileName).ToLower();
if (!AllowedExtensions.Contains(ext)) { errorMessage = "副檔名不允許"; return false; }
return true;
}
}
封裝為可重用控制項,在頁面中直接使用 <cc:ValidatedFileUpload ... />,業務邏輯更乾淨。