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"];
  ...
}
5
  • 2
    stackoverflow.com/questions/5193842/file-upload-asp-net-mvc-3-0/… Commented Nov 27, 2013 at 4:05
  • If I use HttpPostedFileBase, the parameter will be null. Commented Nov 27, 2013 at 4:32
  • use the same name for your input element and method parameter. Follow the link i posted Commented Nov 27, 2013 at 4:37
  • 1
    I've updated the post. I am using the same ID/Name for the input element and method parameter. Still no file. Commented Nov 27, 2013 at 4:48
  • 1
    Got it working with FormCollection. IE was caching my form fields. Once I refreshed, it began working. Commented Nov 27, 2013 at 4:55

2 Answers 2

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");        
}
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of copying and pasting solutions as your own you should really point to the original. stackoverflow.com/a/5193851/1759873
0

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

1 Comment

file is still null. There isn't anything in the Request.Files collection.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.