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

ASP.NET MVC 檔案上傳下載完整指南:從 Html.BeginForm 到 Controller 處理

     編輯:關於ASP.NET

WebForms 開發者轉 MVC 最大文化衝擊:沒有 FileUpload 控制項

MVC View 只需產生標準 HTML <input type="file">,關鍵在 form 標籤加上 enctype="multipart/form-data" 且 method="post"。

兩種寫法產生相同 HTML

純 HTML

<form action="/" method="post" enctype="multipart/form-data">
  <input type="file" name="FileUpload1" /><br />
  <input type="submit" value="Upload" />
</form>

Html.BeginForm 擴充方法(推薦)

<% using (Html.BeginForm("", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
  <input type="file" name="FileUpload1" /><br />
  <input type="submit" value="Upload" />
<% } %>

重點:name="FileUpload1" 將對應 Controller 參數或 Request.Files["FileUpload1"]。

Controller 處理上傳檔案

Request.Files 為 HttpFileCollectionBase,每個元素為 HttpPostedFileBase。擴充方法判斷是否有檔案:

public static bool HasFile(this HttpPostedFileBase file) {
    return file != null && file.ContentLength > 0;
}

完整 Action 範例

public class HomeController : Controller {
    public ActionResult Index() {
        foreach (string upload in Request.Files) {
            if (!Request.Files[upload].HasFile()) continue;

            string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
            string filename = Path.GetFileName(Request.Files[upload].FileName);
            Request.Files[upload].SaveAs(Path.Combine(path, filename));
        }
        return View();
    }
}
  • 遍歷 Request.Files 鍵值集合。
  • HasFile() 過濾空檔案欄位。
  • Path.GetFileName 防止路徑遍歷攻擊。
  • SaveAs 儲存至伺服器磁碟。

檔案下載:回傳 FileResult

public ActionResult Download(string filename) {
    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads", filename);
    if (!System.IO.File.Exists(path)) return HttpNotFound();

    // 依副檔名決定 Content-Type,或統一 application/octet-stream 強制下載
    return File(path, "application/octet-stream", filename);
}

FileResult 自動處理 Content-Disposition: attachment、檔案串流傳輸、大檔案記憶體優化。

安全性檢查表

  • [ ] 限制副檔名/MIME 類型(白名單)。
  • [ ] 限制檔案大小(web.config maxRequestLength / requestLimits maxAllowedContentLength)。
  • [ ] 儲存路徑不可直接對應公開 URL(防止直接下載惡意腳本)。
  • [ ] 檔案名稱重命名(GUID + 原副檔名),避免覆蓋與注入。
  • [ ] 病毒掃描(高安全需求系統)。

MVC 檔案上傳下載本質是標準 HTTP 多部分表單與檔案串流,掌握 Request.Files、HttpPostedFileBase、FileResult 三大核心,即可輕鬆實作企業級檔案管理功能。

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