2013-12-21 22 views
0

我想上傳允許文件上傳在我的MVC應用程序,但是當我測試它的頁面只是刷新,不顯示任何錯誤,並沒有上傳文件,所以我對於什麼是錯誤的完全疏忽。文件上傳不起作用,但沒有丟失任何錯誤

查看:

<form action="" method="post" enctype="multipart/form-data"> 

    <label for="file">Filenname:</label> 
    <input type="file" name="file" id="file" /> 
    <input type="submit" /> 
</form> 

控制器:

[HttpPost] 
    public ActionResult Index(HttpPostedFileBase file) 
    { 
     if (file.ContentLength > 0) 
     { 
      var filename = Path.GetFileName(file.FileName); 
      var path = Path.Combine(Server.MapPath("~/"), filename); 
      file.SaveAs(path); 
     } 

     return RedirectToAction("Index"); 
    } 
+1

你的表單動作是空白 – Jasen

+0

@Jasen我下面http://haacked.com/archive/2010/07/16/uploading-files- with-aspnetmvc.aspx /表單動作應該是什麼?通常是「」的動作意味着張貼到同一頁面,應該由索引ActionResult – Matthew

+1

Jasen抓取是正確的。你需要指定行動的動向 - 與BeginForm –

回答

2

嘗試:

<form action="Controller/Index" method="post" enctype="multipart/form-data"> 

    <label for="file">Filenname:</label> 
    <input type="file" name="file" id="file" /> 
    <input type="submit" /> 
</form> 
+0

這與控制器一起工作,因此'action =「Index」 – Matthew

0

還沒有真正嘗試過,但我的猜測是,那是因爲你沒有使用Html.BeginForm和你正在使用簡單<form>。 試試這個:

@using (Html.BeginForm("Index","Upload",FormMethod.Post, new {enctype="multipart/form-data"})) 
{ 
    <input type="file" name ="file" id ="file"/> 
    <input type="submit"> 
} 
相關問題