2011-08-03 101 views
0

我正在使用文件上傳程序使用httphandler文件(.ashx),但它在普通的.net web appln中工作。現在我試圖在MVC中使用它,但無法做到這一點。任何機構能幫助我解決這個問題或建議任何其他方式。使用處理程序文件在MVC中上傳文件

回答

1

這裏是你如何上傳ASP.NET MVC文件,而無需訴諸的HttpHandler(* .ashx的):

讓我們假設你想創建一個新的用戶配置文件。每個配置文件都有一個名稱和配置文件圖片。

1)聲明一個模型。使用HttpPostedFileBase類型的個人資料照片。

public class ProfileModel 
{ 
    public string Name { get; set; } 
    public HttpPostedFileBase ProfilePicture { get; set; } 
} 

2)使用此模型創建包含可用於創建新配置文件的表單的視圖。不要忘記指定enctype =「multipart/form-data」。

<% using (Html.BeginForm("Add", "Profiles", FormMethod.Post, 
      new { enctype = "multipart/form-data" })) { %> 
    <%=Html.TextBoxFor(m => m.Name)%> 
    <input type="file" id="ProfilePicture" name="ProfilePicture" />  
    <input type="submit" value="Save" /> 
<% }%> 

3)在接受發佈表單的控制器中聲明一個動作方法。在這裏您可以訪問代表上傳文件的流。以下代碼示例將流讀入一個字節數組(緩衝區)。之後,您可以將文件保存到文件系統,數據庫等。

[HttpPost] 
public ActionResult Add(ProfileModel model) 
{ 
    if (model.ProfilePicture != null && model.ProfilePicture.InputStream != null) 
    { 
     var filename = model.ProfilePicture.FileName; 

     var buffer = new byte[model.ProfilePicture.InputStream.Length]; 
     model.ProfilePicture.InputStream.Read(buffer, 0, 
      (int) model.ProfilePicture.InputStream.Length); 

     //... 
    } 
}