萬盛學電腦網

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

ASP.NET 取得 HTML 表單 File 控制項上傳檔案完整路徑與儲存實作

前言

在 ASP.NET 中處理檔案上傳時,開發者常會困惑於如何取得用戶端選取檔案的完整路徑。由於瀏覽器安全性限制,前端 `` 僅提供檔案名稱,無法直接取得本機完整路徑。本文將說明正確的處理方式:透過 `HttpFileCollection` 取得上傳檔案流,並儲存至伺服器或資料庫。

核心程式碼解析

1. 遍歷上傳檔案集合

HttpFileCollection files = HttpContext.Current.Request.Files;
for (int i = 0; i < files.Count; i++)
{
    HttpPostedFile postedFile = files[i];
    // 後續處理...
}

2. 取得檔案名稱與副檔名

string fileName = Path.GetFileName(postedFile.FileName); // 僅取得檔名+副檔名
int dotIndex = fileName.LastIndexOf('.');
string fileExtension = (dotIndex > 0) ? fileName.Substring(dotIndex).ToLower() : "";

3. 產生唯一檔名防止衝突

Guid fileGuid = Guid.NewGuid();
string newFileName = fileGuid.ToString() + fileExtension;

4. 檔案大小驗證(範例限制 2GB)

if (postedFile.ContentLength > 2097151 * 1024) // 2GB
{
    // 顯示錯誤訊息並返回
    return;
}

5. 儲存實體檔案至伺服器

string serverPath = Server.MapPath("~/Upload/") + newFileName;
postedFile.SaveAs(serverPath);

6. 寫入資料庫紀錄(範例使用自訂 Model/BLL)

NRModel.File model = new NRModel.File();
model.Fileid = Guid.NewGuid();
model.Folderid = new Guid(FolderId);
model.Filepath = serverPath;
model.FileNam = fileName;
model.FileSize = postedFile.ContentLength;
model.Decription = TextArea1.Value;
model.CreateOn = DateTime.Now;
// 呼叫 BLL 新增
NRBLL.File bll = new NRBLL.File();
if (bll.FN_AddNewRes(model) > 0)
{
    // 記錄日誌、提示成功
}

完整上傳方法封裝

public void FN_UpFiles()
{
    HttpFileCollection files = HttpContext.Current.Request.Files;
    try
    {
        for (int i = 0; i < files.Count; i++)
        {
            HttpPostedFile postedFile = files[i];
            string fileName = Path.GetFileName(postedFile.FileName);
            int dotIndex = fileName.LastIndexOf('.');
            string fileExtension = (dotIndex > 0) ? fileName.Substring(dotIndex).ToLower() : "";

            Guid fileGuid = Guid.NewGuid();
            string newFileName = fileGuid.ToString() + fileExtension;

            // 檔案大小檢查
            if (postedFile.ContentLength > 2097151 * 1024)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('上傳檔案過大!');", true);
                return;
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                try
                {
                    string savePath = Server.MapPath("~/Upload/") + newFileName;
                    
                    // 資料庫記錄
                    NRModel.File model = new NRModel.File
                    {
                        Fileid = Guid.NewGuid(),
                        Folderid = new Guid(FolderId),
                        Filepath = savePath,
                        FileNam = fileName,
                        FileSize = postedFile.ContentLength,
                        Decription = TextArea1.Value,
                        CreateOn = DateTime.Now,
                        CreateBy = Guid.NewGuid(),
                        ModefyBy = Guid.NewGuid()
                    };

                    NRBLL.File bll = new NRBLL.File();
                    if (bll.FN_AddNewRes(model) > 0)
                    {
                        postedFile.SaveAs(savePath);
                        NR.Error.Log.LogType($"上傳資源 {fileName} 成功!伺服器路徑:{savePath}");
                        ScriptManager.RegisterStartupScript(this, GetType(), "success", "alert('上傳成功!');", true);
                    }
                }
                catch (Exception ex)
                {
                    NR.Error.Log.LogType(ex.ToString());
                }
            }
            else
            {
                Response.Write("上傳檔案不能為空!");
                NR.Error.Log.LogType("檔案不能為空!");
            }
        }
    }
    catch (Exception ex)
    {
        NR.Error.Log.LogType(ex.ToString());
    }
}

常見問題與注意事項

  • 無法取得客戶端完整路徑:瀏覽器出於安全考量,`FileName` 屬性僅回傳檔案名稱,不含本機路徑。這是正常行為,不需嘗試繞過。
  • 大檔案上傳設定:需在 `web.config` 中調整 `maxRequestLength`(KB)與 `executionTimeout`(秒),IIS 7+ 還需設定 `security/requestFiltering/requestLimits maxAllowedContentLength`(Bytes)。
  • 副檔名驗證:實務上建議結合 MIME 型別檢查,防止惡意檔案偽裝上傳。
  • 儲存路徑權限:確保 `~/Upload/` 資料夾已授予 IIS_IUSRS 或應用程式集區身分識別寫入權限。

進階延伸:非同步上傳與進度條

若需提升使用者體驗,可搭配 jQuery Form Plugin、Fine Uploader 或 ASP.NET Core 的 `IFormFile` 實作非同步分塊上傳、進度顯示、拖曳上傳等功能。傳統 Web Forms 亦可透過 `AsyncFileUpload` 控制項或自訂 HttpHandler 達成。


總結:ASP.NET 取得上傳檔案的正確做法是透過 `Request.Files` 取得 `HttpPostedFile` 物件,僅能取得檔名與副檔名,不可取得客戶端完整路徑。儲存時建議使用 GUID 重新命名,並同步寫入資料庫紀錄,做好大小、型別驗證與錯誤處理,即可構建安全可靠的上傳功能。

copyright © 萬盛學電腦網 all rights reserved