0

I am not able to get the uploaded file, it always shows Request.Files.Count as 0.

@using (Html.BeginForm("HandleForm", "Home", new { EncType = "multipart/form-data" }))
{    
    <div>Upload Something: 
        <input type="file" name="uploadedFile" />
    </div>
    <br/>
        <input type="submit" value="Submit" />
} 

Controller Action:

 public ActionResult HandleForm(HttpPostedFileBase uploadedFile)
        {                
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
                    file.SaveAs(path);
                }
            }

            return View("FormResults");
        }

1 Answer 1

2

You are using the wrong overload of BeginForm() and adding a route value for enctype, not a html attribute.

You need to use this overload

@using (Html.BeginForm("HandleForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))`
Sign up to request clarification or add additional context in comments.

4 Comments

It worked for me but, it would have been helpful if you have explained it in detail. Without adding the FormMethod.Post, the action method got hit, but only the file was null. So, I thought FormMethod.Post helps only to fire a post request.
I did explain it. In order to post a file, you need to include the enctype attribute - but your code was not adding it - its was adding a route attribute (look at the action attribute of your form using your code - its was action="/Home/HandleForm?enctype=multipart/form-data - and there was noenctype attribute)
Thanks a lot for you time and comment. Can i do same with @Html.TextBox("uploadedFile", null, new { type = "file" }). In the above example, i used <input type="file" name="uploadedFile" />. If I use @Html.Text, its not showing.
Your @Html.TextBox("uploadedFile", null, new { type = "file" }) will work fine (although you really should be using a view model containing a HttpPostedFileBase UploadedFile property and using @Html.TextBoxFor(m => m.UploadedFile", new { type = "file" }) and the POST method will be public ActionResult HandleForm(yourModel model))

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.