ASP.NET MVC處理文件上傳示例

主要代碼片段如下:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">   
 
<h3>Files uploaded to server</h3>   
 
<div id="dialog" title="Upload files">     
  <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new 


{ 

enctype = "multipart/form-data" 

}

)) 
  {%>

<br /> 
    <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> ;</p><br /> 
    <p><input type="submit" value="Upload file" /></p>     
  <% } %>   
</div> 
<a href="#" οnclick="jQuery('#dialog').dialog('open'); return false">Upload File</a> 
</asp:content> 


然後,我們需要根據BeginForm中FileController和action(Upload)在指定的Controller中處理請求,參考如下代碼: 
 代碼如下:

public void Upload( 
{ 
foreach (string inputTagName in Request.Files) 
{ 
HttpPostedFileBase file = Request.Files[inputTagName]; 
if (file.ContentLength > 0) 
{ 
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads") 
, Path.GetFileName(file.FileName)); 
file.SaveAs(filePath); 
} 
} 
 
RedirectToAction("Index", "File"); 
}
轉自http://www.codes51.com/article/detail_406.html

發佈了33 篇原創文章 · 獲贊 4 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章