2013-11-27 25 views
1

我正在发布一个简单的文本文件到一个asp.net MVC应用程序。当我使用下面的表单发布时,表单参数不是null。但档案是。任何想法我做错了什么?如何将文件发布到asp.net mvc应用程序?

<form method=post action="http://localhost/Home/ProcessIt" 
enctype="application/x-www-form-urlencoded"> 
<input type=file id="thefile" name="thefile" /> 
<input type="submit" name="Submit" /> 
</form> 

在asp.net MVC应用程序:

[HttpPost] 
public ActionResult ProcessIt(FormCollection thefile) 
{ 
    HttpPostedFileBase file = Request.Files["thefile"]; 
    ... 
} 
+2

http://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc-3-0/5193851#5193851 – Shyju

+0

如果我使用HttpPostedFileBase,该参数将是空。 – 4thSpace

+0

为您的输入元素和方法参数使用相同的名称。按照我发布的链接 – Shyju

回答

5

这个工作对我来说:

查看:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="file" /> 
    <input type="submit" value="OK" /> 
} 

控制器:

[HttpPost] 
public ActionResult Index(HttpPostedFileBase file) 
{ 
    // Verify that the user selected a file 
    if (file != null && file.ContentLength > 0) 
    { 
     // extract only the fielname 
     var fileName = Path.GetFileName(file.FileName); 

     // then save on the server... 
     var path = Path.Combine(Server.MapPath("~/uploads"), fileName); 
     file.SaveAs(path); 
    } 
    // redirect back to the index action to show the form once again 
    return RedirectToAction("Index");   
} 
+0

而不是复制和粘贴解决方案作为你自己,你应该真的指向原来的。 http://stackoverflow.com/a/5193851/1759873 –

相关问题