首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET HTML File 控件實現多文件上傳:原生 input 多實例動態添加 + 服務端 HttpFileCollection 批量處理

     編輯:ASP.NET 基礎

方案優勢

  • 零依賴: 無需引入 Uploadify、Plupload、jQuery File Upload 等第三方庫。
  • 原生兼容: 純 HTML <input type="file">,瀏覽器原生支援,移動端友好。
  • 動態增減: JavaScript 克隆 input 節點,用戶可自由增加/重置上傳欄位。
  • 服務端統一處理: Request.Files (HttpFileCollection) 批量遍歷,邏輯集中。

前端頁面 (up3.aspx)

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

後台代碼 (up3.aspx.cs)

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)。

進階擴展建議

  1. 客戶端預覽: FileReader API 讀取圖片生成 DataURL,上傳前縮略圖預覽。
  2. 進度條: 配合 XMLHttpRequest.upload.onprogress + FormData 異步上傳,替換傳統表單提交。
  3. 斷點續傳/分片: 前端 SparkMD5 計算哈希,後端分片合併,適合大文件(>100MB)。
  4. 雲存儲直傳: 獲取 OSS/阿里云/七牛 臨時簽名,瀏覽器直傳雲端,減輕應用服務器帶寬壓力。
  5. 安全加固: 服務端二次驗證 MIME (文件頭 Magic Number)、掃描木馬、禁用腳本執行權限。

總結

此方案以 原生 HTML input + JS 動態增減 + 服務端 HttpFileCollection 遍歷 為核心,代碼量不足 100 行,無任何外部依賴,完美適配中小型項目、內部管理系統、快速原型開發。若面向公網、大文件、高併發,建議演進為分片異步上傳 + 雲存儲直傳架構。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved