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

ASP.NET 多檔案上傳完整實作:前端動態新增與後端批次儲存

     編輯:關於ASP.NET

在早期 ASP.NET WebForms 專案中,實現多檔案上傳常需配合 JavaScript 動態產生 <input type="file"> 元素,再於伺服器端透過 HttpFileCollection 批次處理。本文提供完整可執行的範例碼,涵蓋前端動態介面、後端儲存邏輯與例外處理。

前端頁面:FileUp.aspx

頁面包含一個表單,使用 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>

後端程式碼:FileUp.aspx.cs

核心邏輯位於 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)。

安全性建議

  • 驗證副檔名與 ContentType,拒絕 .exe、.aspx、.ashx 等可執行腳本。
  • 儲存時重新命名檔案(如 Guid + 原副檔名),避免覆蓋與路徑遍歷攻擊。
  • 上傳目錄設定「讀取/寫入」權限,但移除「執行」權限。
  • 考慮使用病毒掃描元件掃描上傳檔案。

現代化替代方案

若專案允許,建議改用 HTML5 <input type="file" multiple> 搭配 jQuery File Upload、DropzoneJS 或 ASP.NET Core 的 IFormFile,提供進度條、拖放、分塊上傳等更佳體驗。

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