在早期 ASP.NET WebForms 專案中,實現多檔案上傳常需配合 JavaScript 動態產生 <input type="file"> 元素,再於伺服器端透過 HttpFileCollection 批次處理。本文提供完整可執行的範例碼,涵蓋前端動態介面、後端儲存邏輯與例外處理。
頁面包含一個表單,使用 enctype="multipart/form-data" 編碼,並透過 JavaScript 函式 addFile() 動態在 <p id="MyFile"> 容器中插入新的檔案輸入框。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUp.aspx.cs" Inherits="TestCenter.FileUp" %>
<!DOCTYPE html>
<html>
<head>
<title>多檔案上傳示範</title>
<script type="text/javascript">
function addFile() {
var container = document.getElementById('MyFile');
var input = document.createElement('input');
input.type = 'file';
input.name = 'File';
input.size = 50;
container.appendChild(input);
container.appendChild(document.createElement('br'));
}
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div style="text-align:center;">
<h3>多檔案上傳</h3>
<p id="MyFile">
<input type="file" name="File" size="50" />
</p>
<p>
<input type="button" value="新增檔案" onclick="addFile()" />
<input type="reset" value="重置" />
<asp:Button ID="UploadButton" runat="server" Text="開始上傳" OnClick="UploadButton_Click" />
</p>
<p>
<asp:Label ID="lblStatus" runat="server" Font-Bold="true" ForeColor="Blue" />
</p>
</div>
</form>
</body>
</html>
核心邏輯位於 SaveImages() 方法,透過 Request.Files 取得 HttpFileCollection,逐一檢查檔案名稱、副檔名、ContentType,並儲存至伺服器 ~/images/ 目錄。
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestCenter
{
public partial class FileUp : Page
{
protected Button UploadButton;
protected Label lblStatus;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) SaveFiles();
}
private void SaveFiles()
{
HttpFileCollection files = Request.Files;
StringBuilder sb = new StringBuilder();
sb.Append("上傳檔案清單:<hr color='red' />");
try
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile postedFile = files[i];
string fileName = Path.GetFileName(postedFile.FileName);
if (!string.IsNullOrEmpty(fileName))
{
string ext = Path.GetExtension(fileName);
sb.AppendFormat("檔案類型:{0}<br />", postedFile.ContentType);
sb.AppendFormat("用戶端路徑:{0}<br />", postedFile.FileName);
sb.AppendFormat("檔案名稱:{0}<br />", fileName);
sb.AppendFormat("副檔名:{0}<hr />", ext);
// 確保目錄存在且具寫入權限
string savePath = Server.MapPath("~/images/") + fileName;
postedFile.SaveAs(savePath);
}
}
lblStatus.Text = sb.ToString();
}
catch (Exception ex)
{
lblStatus.Text = "上傳失敗:" + ex.Message;
}
}
}
}
預設 ASP.NET 限制上傳 4MB,需在 Web.config 調整 <httpRuntime>:
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="300" /> <!-- 100MB, 5分鐘 -->
</system.web>
IIS 7+ 另需設定 <system.webServer><security><requestFiltering><requestLimits maxAllowedContentLength="104857600" /></requestFiltering></security></system.webServer>(單位為 Bytes)。
.exe、.aspx、.ashx 等可執行腳本。若專案允許,建議改用 HTML5 <input type="file" multiple> 搭配 jQuery File Upload、DropzoneJS 或 ASP.NET Core 的 IFormFile,提供進度條、拖放、分塊上傳等更佳體驗。