<input type="file">,瀏覽器原生支援,移動端友好。Request.Files (HttpFileCollection) 批量遍歷,邏輯集中。<%@ Page Language="C#" AutoEventWireup="true" CodeFile="up3.aspx.cs" Inherits="up3" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>多文件上傳演示</title>
<script type="text/javascript">
// 動態添加一個文件輸入框
function addFile() {
var container = document.getElementById("fileContainer");
var div = document.createElement("div");
div.innerHTML = "<input name='File' type='file' /> ";
container.appendChild(div);
}
// 重置為初始狀態(僅保留一個)
function resetFiles() {
var container = document.getElementById("fileContainer");
container.innerHTML = "<div><input name='File' type='file' /></div>";
}
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data"> <!-- 關鍵屬性 -->
<input type="button" value="+ 增加文件" onclick="addFile()" />
<input type="button" value="↻ 重置" onclick="resetFiles()" />
<br /><br />
<div id="fileContainer">
<div><input name="File" type="file" /></div>
</div>
<br />
<asp:Button ID="btnUpload" runat="server" Text="上傳" OnClick="btnUpload_Click" />
<br /><br />
<asp:Label ID="lblMsg" runat="server" ForeColor="Green" />
</form>
</body>
</html>
using System;
using System.IO;
using System.Web.UI;
public partial class up3 : Page
{
protected void btnUpload_Click(object sender, EventArgs e)
{
// 業務配置
const string uploadDir = "~/Uploads/";
const int maxSizeMB = 5;
const string allowedExts = "|.bmp|.jpg|.jpeg|.png|.gif|";
var files = Request.Files; // HttpFileCollection
int total = files.Count;
int success = 0, fail = 0;
var errors = new System.Text.StringBuilder();
for (int i = 0; i < total; i++)
{
var httpFile = files[i];
if (httpFile == null || httpFile.ContentLength == 0) continue; // 空 input 跳過
string origName = Path.GetFileName(httpFile.FileName);
string ext = Path.GetExtension(origName).ToLower();
// 1. 擴展名驗證
if (!allowedExts.Contains("|" + ext + "|"))
{
fail++; errors.AppendFormat("第{0}個【{1}】類型不允許;", i + 1, origName);
continue;
}
// 2. 大小驗證
if (httpFile.ContentLength > maxSizeMB * 1024 * 1024)
{
fail++; errors.AppendFormat("第{0}個【{1}】超過{2}MB;", i + 1, origName, maxSizeMB);
continue;
}
// 3. 生成唯一文件名:時間戳 + 隨機數 + 原擴展名
string newName = DateTime.Now.ToString("yyyyMMddHHmmssfff")
+ new Random().Next(1000, 9999) + ext;
string savePath = Server.MapPath(uploadDir + newName);
// 4. 確保目錄存在
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
try
{
httpFile.SaveAs(savePath);
success++;
}
catch (Exception ex)
{
fail++; errors.AppendFormat("第{0}個【{1}】保存失敗:{2};", i + 1, origName, ex.Message);
}
}
lblMsg.Text = $"總計 {total} 個文件,成功 {success},失敗 {fail}。{errors}";
}
}
| 點 | 說明 |
|---|---|
enctype="multipart/form-data" | form 必須設置,否則 Request.Files 永為空。 |
name="File" 統一名稱 | 所有動態 input 共用同一 name,服務端自動聚合為集合。 |
Request.Files[i].ContentLength == 0 | 判斷用戶是否在該 input 選擇了文件,未選則跳過。 |
| 文件名衝突處理 | 時間戳 + 4位隨機數,極低概率衝突;高併發建議加 GUID。 |
| 目錄權限 | IIS_IUSRS / ApplicationPoolIdentity 需對 Uploads 目錄有寫入權限。 |
| 大文件支援 | web.config 需配置 <httpRuntime maxRequestLength="102400" /> (單位 KB,此例 100MB)。 |
XMLHttpRequest.upload.onprogress + FormData 異步上傳,替換傳統表單提交。此方案以 原生 HTML input + JS 動態增減 + 服務端 HttpFileCollection 遍歷 為核心,代碼量不足 100 行,無任何外部依賴,完美適配中小型項目、內部管理系統、快速原型開發。若面向公網、大文件、高併發,建議演進為分片異步上傳 + 雲存儲直傳架構。