萬盛學電腦網

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

ASP.NET 檔案上傳完整指南:三種基本方法、進階上傳類別與檔案驗證、水印處理

三種基本上傳方式比較

方式控制項/物件取得檔名判斷是否有檔案儲存方法封裝程度
1. Web 控制項 FileUpload FileUpload1.FileName (僅檔名) FileUpload1.HasFile SaveAs(path) 最高,最方便
2. HTML 伺服器控制項 HtmlInputFile (runat="server") file1.PostedFile.FileName (IE 含完整路徑,Chrome 僅檔名) file1.PostedFile.ContentLength > 0 PostedFile.SaveAs(path) 中等
3. 原生 HTML + Request.Files <input type="file" name="file"> Request.Files["file"].FileName (瀏覽器差異同方式 2) Request.Files["file"].ContentLength > 0 Request.Files["file"].SaveAs(path) 最低,最靈活

方式一:FileUpload 控制項 (推薦)

<!-- Test.aspx -->
<form id="form1" runat="server" enctype="multipart/form-data">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
    <asp:Label ID="Label1" runat="server" ForeColor="Red" />
</form>

// Test.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        string savePath = Server.MapPath("~/Uploads/") + FileUpload1.FileName;
        FileUpload1.SaveAs(savePath);
        Label1.Text = "上傳成功!";
    }
}

方式二:HtmlInputFile

<form id="form1" runat="server" enctype="multipart/form-data">
    <input type="file" id="file1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
    <asp:Label ID="Label1" runat="server" ForeColor="Red" />
</form>

protected void Button1_Click(object sender, EventArgs e)
{
    if (file1.PostedFile.ContentLength > 0)
    {
        string fileName = Path.GetFileName(file1.PostedFile.FileName); // 統一只取檔名
        string savePath = Server.MapPath("~/Uploads/") + fileName;
        file1.PostedFile.SaveAs(savePath);
        Label1.Text = "上傳成功!";
    }
}

方式三:Request.Files

<form id="form1" runat="server" enctype="multipart/form-data">
    <input type="file" name="file" />
    <asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
    <asp:Label ID="Label1" runat="server" ForeColor="Red" />
</form>

protected void Button1_Click(object sender, EventArgs e)
{
    HttpPostedFile postedFile = Request.Files["file"];
    if (postedFile != null && postedFile.ContentLength > 0)
    {
        string fileName = Path.GetFileName(postedFile.FileName);
        string savePath = Server.MapPath("~/Uploads/") + fileName;
        postedFile.SaveAs(savePath);
        Label1.Text = "上傳成功!";
    }
}

關鍵差異總結

  • 檔名取得差異:`FileUpload.FileName` 永遠只回傳檔名;`PostedFile.FileName` 在 IE 含完整客戶端路徑 (C:\path\file.jpg),現代瀏覽器僅檔名 → **務必使用 `Path.GetFileName()` 統一處理**。
  • HasFile vs ContentLength:`FileUpload` 提供語意清晰的 `HasFile`;HTML 控制項需檢查 `ContentLength > 0`。
  • 表單編碼:`
    ` **必須**設定 `enctype="multipart/form-data"`,否則 `Request.Files` 為空。

進階:封裝上傳類別 UploadObj (副檔名驗證、隨機重命名、文字浮水印)

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;

namespace EC
{
    public class UploadObj
    {
        public enum FileType { jpg, gif, bmp, png }

        // 取得副檔名
        public static string GetFileExtends(string filename)
        {
            if (string.IsNullOrEmpty(filename)) return null;
            int idx = filename.LastIndexOf('.');
            return idx > 0 ? filename.Substring(idx + 1).ToLower() : null;
        }

        // 驗證副檔名是否允許
        public static bool CheckFileExtends(string ext)
        {
            if (string.IsNullOrEmpty(ext)) return false;
            foreach (string allowed in Enum.GetNames(typeof(FileType)))
                if (allowed.Equals(ext, StringComparison.OrdinalIgnoreCase)) return true;
            return false;
        }

        // 儲存檔案 (自動重命名避免衝突)
        public static string PhotoSave(string folderPath, FileUpload fu)
        {
            if (!fu.HasFile) return string.Empty;

            string ext = GetFileExtends(fu.FileName);
            if (!CheckFileExtends(ext))
                throw new Exception("上傳檔案類型不合法");

            string newName = $"{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid():N}.{ext}";
            string fullPath = Path.Combine(folderPath, newName);

            try
            {
                fu.SaveAs(fullPath);
            }
            catch (Exception ex)
            {
                throw new Exception("儲存失敗: " + ex.Message);
            }
            return newName;
        }

        // 文字浮水印 (僅示範核心邏輯)
        public void AddTextWatermark(string imagePath, string text, string fontFamily = "Arial", int fontSize = 20, Color? color = null, int opacity = 128)
        {
            if (!File.Exists(imagePath)) throw new FileNotFoundException("圖片不存在", imagePath);

            using (Image img = Image.FromFile(imagePath))
            using (Graphics g = Graphics.FromImage(img))
            using (Font font = new Font(fontFamily, fontSize, FontStyle.Bold))
            using (Brush brush = new SolidBrush(Color.FromArgb(opacity, color ?? Color.White)))
            {
                StringFormat sf = new StringFormat { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Far };
                g.DrawString(text, font, brush, img.Width - 10, img.Height - 10, sf);
                
                // 覆寫原檔或另存新檔
                img.Save(imagePath, img.RawFormat);
            }
        }
    }
}

使用範例

protected void btnUpload_Click(object sender, EventArgs e)
{
    string uploadFolder = Server.MapPath("~/Uploads/");
    if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);

    try
    {
        string savedName = UploadObj.PhotoSave(uploadFolder, FileUpload1);
        string fullPath = Path.Combine(uploadFolder, savedName);
        
        // 可選:加入浮水印
        // new UploadObj().AddTextWatermark(fullPath, "© MySite 2024");

        lblMsg.Text = $"上傳成功:{savedName}";
    }
    catch (Exception ex)
    {
        lblMsg.Text = "錯誤:" + ex.Message;
    }
}

安全性與效能檢查清單

  • ✅ **副檔名白名單驗證** (而非黑名單)
  • ✅ **MIME 類型二次檢查** (`postedFile.ContentType` 可偽造,建議讀取檔頭 Magic Bytes 驗證)
  • ✅ **檔案大小限制** (`web.config` `` 限制 10MB;IIS `requestLimits maxAllowedContentLength`)
  • ✅ **儲存路徑非 Web 可執行目錄** (防止上傳 .aspx/.ashx/.php 執行腳本)
  • ✅ **檔案重命名** (GUID/時間戳/雜湊) 避免覆蓋與路徑遍歷攻擊
  • ✅ **病毒掃描整合** (ClamAV、Windows Defender API) 高安全需求環境
  • ✅ **非同步/分塊上傳** (大檔案 > 100MB 建議 Plupload、FineUploader + Web API 分塊合併)

總結

ASP.NET 提供三種層級的檔案上傳 API,`FileUpload` 封裝度最高最適合一般開發;`Request.Files` 靈活度最高適合處理多檔、非標準表單。務必落實副檔名白名單、檔案重命名、儲存目錄隔離、請求大小限制等安全措施。進階需求 (水印、縮圖、轉檔、分塊) 建議引入 ImageSharp、SkiaSharp、FFmpeg 等專業庫處理。

copyright © 萬盛學電腦網 all rights reserved