ASP.NET 2.0 引入 FileUpload、Calendar、AdRotator、MultiView、Wizard 等豐富控件。本文聚焦 FileUpload,涵蓋基本用法、檔案型別驗證、儲存路徑管理、大檔案與安全性考量,提供可直接套用的完整範例。
| 成員 | 說明 |
|---|---|
HasFile | 布林值,判斷使用者是否已選檔案 |
FileName | 用戶端原始檔名(含路徑,僅 IE 完整) |
FileBytes | 位元組陣列,適合直接寫入資料庫或記憶體處理 |
PostedFile | HttpPostedFile 物件,提供 ContentLength, ContentType, InputStream |
SaveAs(path) | 將檔案儲存至伺服器指定路徑 |
protected void btnUpload_Click(object sender, EventArgs e)
{
if (!fuFile.HasFile) return;
// 1. 檔案型別白名單驗證
string ext = Path.GetExtension(fuFile.FileName).ToLower();
string[] allowed = { ".jpg", ".jpeg", ".png", ".gif", ".pdf" };
if (!allowed.Contains(ext))
{
lblMsg.Text = "不支援的檔案類型";
return;
}
// 2. 確保儲存目錄存在
string saveDir = Server.MapPath("~/Uploads/");
if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
// 3. 產生唯一檔名避免覆蓋
string uniqueName = $"{Guid.NewGuid():N}{ext}";
string fullPath = Path.Combine(saveDir, uniqueName);
// 4. 儲存
fuFile.SaveAs(fullPath);
// 5. 記錄資料庫 / 重新繫結列表
// Insert into DB: FileName, UniqueName, UploadTime, UserId...
BindFileList();
}
<!-- web.config -->
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="600" /> <!-- 100MB, 10分鐘 -->
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600" /> <!-- IIS 7+ 需同步設定 (bytes) -->
</requestFiltering>
</security>
</system.webServer>
web.config 封鎖腳本執行。accept 屬性限制檔案選擇對話框:<asp:FileUpload ID="fu" runat="server" accept="image/*,.pdf" />allowmultiple="true" (HTML5) 或多個 FileUpload 控件動態產生。FileUpload 雖簡單,但生產環境需嚴謹處理安全、效能、體驗三面向。建立標準化上傳元件庫,內建驗證、重命名、日誌、掃毒管線,可大幅降低風險與維護成本。