MVC View 只需產生標準 HTML <input type="file">,關鍵在 form 標籤加上 enctype="multipart/form-data" 且 method="post"。
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="FileUpload1" /><br />
<input type="submit" value="Upload" />
</form>
<% 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"]。
Request.Files 為 HttpFileCollectionBase,每個元素為 HttpPostedFileBase。擴充方法判斷是否有檔案:
public static bool HasFile(this HttpPostedFileBase file) {
return file != null && file.ContentLength > 0;
}
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 儲存至伺服器磁碟。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、檔案串流傳輸、大檔案記憶體優化。
web.config maxRequestLength / requestLimits maxAllowedContentLength)。MVC 檔案上傳下載本質是標準 HTTP 多部分表單與檔案串流,掌握 Request.Files、HttpPostedFileBase、FileResult 三大核心,即可輕鬆實作企業級檔案管理功能。