ASP.NET 預設限制上傳檔案大小為 **4 MB**,超過會拋出例外。本文說明如何修改 `Web.config` 突破限制,並提供完整上傳程式碼範例與關鍵注意事項。
<system.web>
<!--
maxRequestLength:最大請求長度(單位:KB),預設 4096 (4MB)
executionTimeout:請求執行逾時(單位:秒),預設 110 秒
-->
<httpRuntime maxRequestLength="40960" executionTimeout="6000" />
</system.web>
上例將上傳上限設為 **40 MB**(40960 KB),逾時設為 **6000 秒**(100 分鐘),適合大檔案上傳。
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength:單位為 Bytes,預設 30000000 (~28.6MB) -->
<requestLimits maxAllowedContentLength="41943040" /> <!-- 40 MB -->
</requestFiltering>
</security>
</system.webServer>
<asp:FileUpload ID="fulFileName" runat="server" />
<asp:TextBox ID="txtFileName" runat="server" placeholder="自訂檔名(不含副檔名)" />
<asp:Button ID="btnSend" Text="上傳" OnClick="btnSend_Click" runat="server" />
<asp:Label ID="lblResult" runat="server" />
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
if (!fulFileName.HasFile)
{
lblResult.Text = "請先選擇檔案";
return;
}
// 1. 取得原始檔名與副檔名
string originalName = fulFileName.FileName; // 瀏覽器可能只回傳檔名,不含路徑
string extension = Path.GetExtension(originalName); // 含點號,如 ".pdf"
// 2. 組合新檔名(使用者輸入 + 原副檔名)
string newFileName = txtFileName.Text.Trim() + extension;
if (string.IsNullOrWhiteSpace(txtFileName.Text))
{
newFileName = originalName; // 未輸入則保留原名
}
// 3. 目標儲存路徑(專案根目錄下的 File 資料夾)
string folderPath = Server.MapPath("~/File/");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath); // 自動建立資料夾
}
string fullPath = Path.Combine(folderPath, newFileName);
// 4. 儲存檔案
fulFileName.PostedFile.SaveAs(fullPath);
lblResult.Text = $"上傳成功:{newFileName} ({fulFileName.PostedFile.ContentLength} bytes)";
}
catch (Exception ex)
{
lblResult.Text = "上傳失敗:" + ex.Message;
// 建議記錄完整堆疊至 Log
}
}
| 錯誤現象 | 可能原因 | 解決方向 |
|---|---|---|
| HTTP 404.13 / 最大內容長度超過 | IIS `maxAllowedContentLength` 太小 | 設定 `system.webServer/security/requestFiltering/requestLimits` |
| HTTP 500 / 逾時 | `executionTimeout` 過短 | 增加 `httpRuntime executionTimeout` |
| 儲存失敗:存取被拒 | 資料夾寫入權限不足 | 授予 IIS_IUSRS / AppPool Identity 寫入權限 |
| 檔名亂碼 | 瀏覽器編碼差異 | 使用 `HttpUtility.UrlDecode` 或 Guid 重命名 |
正確配置 `maxRequestLength` 與 `maxAllowedContentLength`,搭配健全的後端儲存邏輯,即可在 ASP.NET Web Forms 中穩定支援大檔案上傳。