0

I don't know what I'm missing, but I need to upload a file using C# MVC 3. I followed instructions here in SO, but the file is always empty.

Here is my actual testing code:

HTML

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

Controller

[HttpPost]
public ActionResult Prc(HttpPostedFile file)
{
    if (file != null && file.ContentLength > 0)
    {
        var filename = System.IO.Path.GetFileName(file.FileName);
        var path = System.IO.Path.Combine(Server.MapPath("~/Content/Images"), filename);
        file.SaveAs(path);            
     }

     return RedirectToAction("Index");
 }

When I run the web app, I attach a file, and click Submit. But when I reach the Controller, the file object is null. Always null. I tried an XML file, a JPEG file, and a GIF file but none of them worked.

Should I configure something else besides just these codes?

Thanks

2 Answers 2

2

In MVC you need to use HttpPostedFileBase instead of the HttpPostedFile:

[HttpPost]
public ActionResult Prc(HttpPostedFileBase file)
{
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

2

One more thing might trip you up.

Using asp.net mvc 3 razor, I was just surprised to discover that the name of the HttpPostedFileBase variable passed to the controller method must match the id and name of the file input tag on the the view. Otherwise asp.net passes null for the HttpPostedFileBase variable.

For example, if your file input looks like this: < input type="file" name="filex" id="filex" />

And your controller method looks like this: public ActionResult Uploadfile(HttpPostedFileBase filey)

You'll get NULL for the "filey" variable. But rename "filey" to "filex" in your controller method and it posts the file successfully.

2 Comments

Tom, good call out. Your post here just pulled me out of a few hours of trouble.
Yeah, same here! I was stuck and it was this stupid thing! thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.