ASP.NET MVC 1.0 中實現檔案上傳相當直觀,關鍵在於表單設定 enctype="multipart/form-data"、HttpPostedFileBase 模型繫結,以及單元測試的 Mock 技巧。
<% using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { enctype = "multipart/form-data" })) {%>
<table>
<tr><td><input type="file" id="picture" name="picture" /></td></tr>
<tr><td><input type="submit" value="Upload" /></td></tr>
</table>
<% } %>
重點:input type="file" 必須有 name 屬性,對應後端參數名稱。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(HttpPostedFileBase picture)
{
if (picture != null)
{
picture.SaveAs(@"C:\wherever\" + picture.FileName);
}
return View();
}
MVC 模型繫結器自動將上傳檔案繫結至 HttpPostedFileBase 參數,SaveAs 方法直接儲存至伺服器路徑。
var personPicture = new Mock<HttpPostedFileBase>();
personPicture.Setup(i => i.FileName).Returns("person.jpg");
personPicture.Setup(i => i.InputStream).Returns(new MemoryStream(Encoding.UTF8.GetBytes("")));
var controller = new PersonController();
controller.Edit(personPicture.Object);
personPicture.Verify(p => p.SaveAs(@"C:\wherever\person.jpg"));
使用 Moq 建立 HttpPostedFileBase 模擬物件,設定 FileName 與 InputStream 行為,驗證 SaveAs 是否以正確路徑被呼叫。這展示了 MVC 可測試性的核心優勢——無需真實檔案即可完整驗證上傳邏輯。
HttpHandler 管控存取權限。