Asp.net MVC 1.0 RTM中實現檔案上傳

來源:互聯網
上載者:User

在我們開始之前,你需要知道一個form以post方式上傳檔案的方式,你將要增加一個特別的enctype attribute到form標籤上,為了這個麼,我們需要建立一個像這樣的form標籤:

<% using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { enctype = "multipart/form-data" })) {%>

然後我們只需要增加一個Type為"file"的input,一個sumbit按鈕的表單.你必須確保input上有"name" attribute.我們也能任何一個我們想要的form上:

<table>    <tr>        <td><input type="file" id="picture" name="picture" /></td>    </tr>    <tr>        <td><input type="submit" value="Upload" /></td>    </tr></table>

現在我們自己的表單了,準備好伺服器端的Action.我們這麼做:

[AcceptVerbs(HttpVerbs.Post)]public ActionResult Edit(HttpPostedFileBase picture){    if (picture != null)    {        picture.SaveAs("C:\wherever\" + picture.FileName);    }}

漂亮吧!現在只剩下測試它了.我使用了Moq 3,我們只需要mock出一個檔案,並放入方法中:

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");

哇.所有能mock出所有我們有的東西,假裝控制器中少許屬性,調用方法,然後驗證圖片上適當的方法是否被調用.就是那麼簡單!

希望你已知道這些,但如果你不知,希望這篇post能幫到你.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.