萬盛學電腦網

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

ASP.NET 簡單易用檔案上傳類:UploadFile 完整實作與使用指南

單檔上傳元件:支援自訂路徑、檔名策略、類型驗證、衝突處理

封裝 `HttpPostedFile` 操作,提供流暢介面配置上傳行為,回傳結構化結果物件。

使用範例

var uf = new UploadFile();
uf.SetIsUseOldFileName(true)          // true=保留原檔名, false=系統產生 GUID 檔名
  .SetFileDirectory(Server.MapPath("/file/temp3/"))  // 儲存實體目錄
  .SetFileType("*")                   // 允許類型,逗號分隔,* 表全部
  .SetIsRenameSameFile(false);        // 同名檔案是否重新命名

// 依日期分資料夾:/file/temp3/2024/5/xxx.jpg
var result = uf.Save(Request.Files["Fileupload1"]);

// 依編號分資料夾:/file/temp3/001/xxx.jpg
var result2 = uf.Save(Request.Files["Fileupload1"], "001");

// 結果判斷
if (!result.Error)
{
    string webPath = result.WebFilePath;  // 相對網站根目錄路徑
    string physicalPath = result.FilePath; // 伺服器實體路徑
}
else
{
    string msg = result.Message;  // 錯誤訊息
}

UploadFile 類別完整程式碼

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

public class UploadFile
{
    private string _saveDir = "/upload";
    private string _allowedTypes = ".pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif";
    private bool _useOriginalName = true;
    private bool _renameIfExists = false;
    
    public UploadFile SetFileDirectory(string dir) { _saveDir = dir; return this; }
    public UploadFile SetFileType(string types) { _allowedTypes = types.ToLower(); return this; }
    public UploadFile SetIsUseOriginalFileName(bool use) { _useOriginalName = use; return this; }
    public UploadFile SetIsRenameSameFile(bool rename) { _renameIfExists = rename; return this; }

    public UploadResult Save(HttpPostedFile file, string subFolder = null)
    {
        var result = new UploadResult();
        if (file == null || file.ContentLength == 0)
        {
            result.Error = true; result.Message = "無檔案或檔案為空";
            return result;
        }

        // 1. 檢查副檔名
        string ext = Path.GetExtension(file.FileName).ToLower();
        if (_allowedTypes != "*" && !_allowedTypes.Split(',').Contains(ext))
        {
            result.Error = true; result.Message = $"不允許的檔案類型:{ext}";
            return result;
        }

        // 2. 決定檔名
        string fileName = _useOriginalName ? Path.GetFileName(file.FileName) 
            : Guid.NewGuid().ToString("N") + ext;

        // 3. 組合儲存路徑
        string saveDir = _saveDir;
        if (!String.IsNullOrEmpty(subFolder))
            saveDir = Path.Combine(saveDir, subFolder);
        
        if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
        
        string fullPath = Path.Combine(saveDir, fileName);

        // 4. 處理同名檔案
        if (File.Exists(fullPath))
        {
            if (_renameIfExists)
                fileName = $"{Path.GetFileNameWithoutExtension(fileName)}_{DateTime.Now:yyyyMMddHHmmss}{ext}";
            else
            {
                result.Error = true; result.Message = "檔案已存在";
                return result;
            }
            fullPath = Path.Combine(saveDir, fileName);
        }

        // 5. 儲存
        try
        {
            file.SaveAs(fullPath);
            result.Error = false;
            result.FilePath = fullPath;
            result.WebFilePath = VirtualPath(fullPath);
            result.Message = "上傳成功";
        }
        catch (Exception ex)
        {
            result.Error = true; result.Message = "儲存失敗:" + ex.Message;
        }
        return result;
    }

    private string VirtualPath(string physicalPath)
    {
        // 將實體路徑轉為網站相對路徑 (需根據實際部署調整)
        string webRoot = HttpContext.Current.Server.MapPath("~");
        if (physicalPath.StartsWith(webRoot))
            return "~/" + physicalPath.Substring(webRoot.Length).Replace('\\', '/');
        return physicalPath;
    }
}

public class UploadResult
{
    public bool Error { get; set; }
    public string Message { get; set; }
    public string FilePath { get; set; }      // 伺服器實體路徑
    public string WebFilePath { get; set; }   // 網站相對路徑 (含 ~/)
}

安全性加強清單

  • **副檔名雙重驗證**:`Path.GetExtension` + `FileUpload.PostedFile.ContentType` MIME 比對。
  • **檔案內容掃描**:上傳後用 ClamAV/Windows Defender 掃毒,或檢查 Magic Number (檔頭位元組)。
  • **儲存路徑隔離**:上傳目錄**不可執行腳本** (IIS 設定 `Execute Permissions = None`)。
  • **檔名去識別化**:預設使用 GUID 檔名,避免路徑遍歷、中文檔名編碼問題。
  • **大小限制**:`web.config` `` (KB) + `` (Bytes)。

多檔上傳擴充 (HTML5 multiple)

public List SaveMultiple(HttpFileCollection files, string subFolder = null)
{
    var results = new List();
    for (int i = 0; i < files.Count; i++)
        results.Add(Save(files[i], subFolder));
    return results;
}

ASP.NET Core 版本: 使用 `IFormFile`、`IWebHostEnvironment.WebRootPath`、依賴注入 `IFileStorageService`,支援雲端儲存 (Azure Blob/AWS S3/MinIO) 介面抽象。

copyright © 萬盛學電腦網 all rights reserved