2010-12-06 67 views
1

我試圖讓我的MVC項目文件上載到服務器。我寫了我的課,C#MVC問題,文件上傳

public class MyModule: IHttpModule 

which defines the event 

void app_BeginRequest (object sender, EventArgs e) 

In it, I check the length of the file that the user has selected to send. 

if (context.Request.ContentLength> 4096000) 
{ 
    //What should I write here, that file is not loaded? I tried 
    context.Response.Redirect ("address here"); 
    //but the file is still loaded and then going on Redirect. 
} 
+0

你到底要做 - 檢查文件是否超過最大尺寸?另外,我不認爲你需要創建的IHttpModule的實現來處理文件上傳 - 你可以簡單地在你的控制器,需要一個HttpPostedFileBase參數使用[HttpPost]操作。 – Pandincus 2010-12-06 14:26:55

回答

5

在ASP.NET MVC中,您通常不會編寫http模塊來處理文件上載。您編寫控制器並在您編寫操作的控制器內部執菲爾哈克blogged有關文件上傳妮ASP.NET MVC:

你必須包含表單視圖:

<% using (Html.BeginForm("upload", "home", FormMethod.Post, 
    new { enctype = "multipart/form-data" })) { %> 
    <label for="file">Filename:</label> 
    <input type="file" name="file" id="file" /> 

    <input type="submit" /> 
<% } %> 

和控制器動作來處理上傳:

[HttpPost] 
public ActionResult Upload(HttpPostedFileBase file) 
{ 
    if (file != null && file.ContentLength > 0) 
    { 
     if (file.ContentLength > 4096000) 
     { 
      return RedirectToAction("FileTooBig"); 
     } 
     var fileName = Path.GetFileName(file.FileName); 
     var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
     file.SaveAs(path); 
    } 
    return RedirectToAction("Index"); 
} 
+0

當觸發事件上傳時,文件已經上傳到服務器。如果文件大於某個值,我不想加載它。 – Stillus 2010-12-06 14:33:06