萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 檔案上傳完整實作:驗證、儲存、安全性與大檔案支援

前端表單 (ASPX)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="Demo.Upload" %>
<form id="form1" runat="server" enctype="multipart/form-data">
    <asp:FileUpload ID="fuFile" runat="server" />
    <asp:Button ID="btnUpload" Text="上傳" OnClick="btnUpload_Click" runat="server" />
    <asp:Label ID="lblMsg" runat="server" ForeColor="Red" />
    <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="檔名" />
            <asp:BoundField DataField="Size" HeaderText="大小(KB)" DataFormatString="{0:N1}" />
            <asp:BoundField DataField="Type" HeaderText="類型" />
            <asp:HyperLinkField DataNavigateUrlFields="Path" DataTextField="Path" HeaderText="下載" />
        </Columns>
    </asp:GridView>
</form>

後端代碼 (C#) - 含驗證與安全防護

public partial class Upload : System.Web.UI.Page
{
    private readonly string[] _allowedExt = { ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip", ".rar", ".txt" };
    private const long MaxFileSize = 20 * 1024 * 1024; // 20 MB
    private readonly string _saveRoot = "~/App_Data/Uploads/";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) BindGrid();
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (!fuFile.HasFile) { Show("請選擇檔案"); return; }

        // 1. 副檔名驗證 (不區分大小寫)
        string ext = Path.GetExtension(fuFile.FileName).ToLowerInvariant();
        if (Array.IndexOf(_allowedExt, ext) < 0)
        { Show($"不允許的檔案類型:{ext}"); return; }

        // 2. 檔案大小驗證
        if (fuFile.FileBytes.Length > MaxFileSize)
        { Show($"檔案過大,限制 {MaxFileSize / 1024 / 1024} MB"); return; }

        // 3. 內容型別二次驗證 (防止偽裝副檔名)
        string mime = fuFile.PostedFile.ContentType;
        if (!IsMimeAllowed(ext, mime))
        { Show("檔案內容與副檔名不符,疑似偽裝"); return; }

        // 4. 安全儲存:重新命名避免覆蓋、路徑遍歷
        string safeName = $"{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid():N}{ext}";
        string virtualPath = VirtualPathUtility.Combine(_saveRoot, safeName);
        string physicalPath = Server.MapPath(virtualPath);

        Directory.CreateDirectory(Path.GetDirectoryName(physicalPath));
        fuFile.SaveAs(physicalPath);

        // 5. 記錄資料庫 (略) → 重新繫結
        Show($"上傳成功:{safeName}");
        BindGrid();
    }

    private bool IsMimeAllowed(string ext, string mime)
    {
        // 簡易對照,實務建議用 FileSignature (Magic Number) 檢測
        return ext switch
        {
            ".jpg" or ".jpeg" => mime == "image/jpeg",
            ".png" => mime == "image/png",
            ".gif" => mime == "image/gif",
            ".pdf" => mime == "application/pdf",
            ".zip" => mime == "application/zip",
            ".rar" => mime == "application/x-rar-compressed",
            _ => true // 其餘僅驗證副檔名
        };
    }

    private void BindGrid()
    {
        // 實務從資料庫讀取檔案清單,此處示範掃描目錄
        var dir = new DirectoryInfo(Server.MapPath(_saveRoot));
        var files = dir.GetFiles().Select(f => new
        {
            Name = f.Name,
            Size = f.Length / 1024.0,
            Type = GetMimeFromExt(f.Extension),
            Path = VirtualPathUtility.Combine(_saveRoot, f.Name)
        });
        gvFiles.DataSource = files; gvFiles.DataBind();
    }

    private void Show(string msg) => lblMsg.Text = $"[{DateTime.Now:HH:mm:ss}] {msg}";
}

Web.config 大檔案上傳設定

<system.web>
  <!-- 最大要求長度 (KB),預設 4096 = 4MB -->
  <httpRuntime maxRequestLength="20480" executionTimeout="300" /> <!-- 20MB, 5分鐘 -->
</system.web>
<system.webServer>
  <security>
    <requestFiltering>
      <!-- 最大內容長度 (Bytes),預設 30000000 ≈ 28.6MB -->
      <requestLimits maxAllowedContentLength="20971520" /> <!-- 20MB -->
    </requestFiltering>
  </security>
</system.webServer>

進階:大檔案分塊上傳 (Chunked Upload)

超過 100MB 檔案建議採用前端分片 (如 Resumable.js、Uppy、FineUploader) + 後端合併,避免 IIS 要求長度限制與記憶體壓力。核心流程:

  1. 前端切片 (預設 5MB/片) → 並行 POST 至 `/api/upload/chunk`
  2. 後端儲存暫存片段 `Guid_partIndex.tmp`
  3. 所有片段上傳完成 → 前端呼叫 `/api/upload/merge` → 後端合併並驗證雜湊

安全性檢查清單

  • ✅ 儲存路徑在 `App_Data` 或 Web 根目錄外,無法直接 HTTP 存取
  • ✅ 副檔名白名單 + MIME 型別雙重驗證
  • ✅ 檔案重新命名 (Guid + 時間戳) 防覆蓋與路徑遍歷
  • ✅ 限制單檔大小與總上傳大小
  • ✅ 伺服器端掃毒 (整合 ClamAV / Windows Defender)
  • ✅ 圖片重新壓縮/去除 EXIF (防止圖片藏毒)
copyright © 萬盛學電腦網 all rights reserved