如何将文件发布到asp.net mvc app?

4th*_*ace 1 c# asp.net-mvc

我将一个简单的文本文件发布到asp.net MVC应用程序.当我使用下面的表单发布时,表单参数不为null.但文件是.我有什么想法我做错了吗?

<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>
Run Code Online (Sandbox Code Playgroud)

在asp.net mvc应用程序中:

[HttpPost]
public ActionResult ProcessIt(FormCollection thefile)
{
  HttpPostedFileBase file = Request.Files["thefile"];
  ...
}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*yas 5

这对我有用:

视图:

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

控制器:

[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");        
}
Run Code Online (Sandbox Code Playgroud)