萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> .NET 程式設計

ASP.NET FileUpload 檔案上傳大小限制:前端驗證與 web.config maxRequestLength 雙重保護

檔案上傳雙重防護策略

  1. 前端程式碼檢查:FileUpload.PostedFile.ContentLength 即時攔截超大檔案
  2. 伺服器端配置限制:httpRuntime maxRequestLength 防止惡意繞過前端上傳超大請求

前端完整範例 (ASPX)

<%@ 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>

伺服器端配置 (Web.config)

<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 版本
maxRequestLengthsystem.web/httpRuntimeKBASP.NET 管道所有版本
maxAllowedContentLengthsystem.webServer/security/requestFiltering/requestLimitsBytesIIS 核心 (早於 ASP.NET)IIS 7.0+

常見問題與解決

  • 上傳大檔案報 404.13 / 500:未設定 maxAllowedContentLength (IIS 7+)
  • 上傳超過限制無任何反應/白畫面:ASP.NET 攔截拋出 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 ... />,業務邏輯更乾淨。

copyright © 萬盛學電腦網 all rights reserved