1

I'm posting a simple text file to an asp.net MVC app. When I post using the form below, the form parameter is not null. But file is. Any ideas what I'm doing wrong?

<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>

In the asp.net mvc app:

[HttpPost]
public ActionResult ProcessIt(FormCollection thefile)
{
  HttpPostedFileBase file = Request.Files["thefile"];
  ...
}
4thSpace
  • 43,672
  • 97
  • 296
  • 475

2 Answers2

5

This works for me:

View:

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

Controller:

[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");        
}
Ahmed ilyas
  • 5,722
  • 8
  • 44
  • 72
0

Need to change the enctype to multipart/form-data: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

Tieson T.
  • 20,774
  • 6
  • 77
  • 92