How to upload file in ASP.Net MVC

Posted by Anuraj on Tuesday, May 6, 2014

.Net .Net 4.0 ASP.Net MVC

This post is about upload file to server using ASP.Net MVC 4. First you need to modify the controller to accept the posted file along with the model. So you can modify it like this.

[HttpPost]
public ActionResult UploadImage(Student student, HttpPostedFileBase image)
{
    var imageFile = 
        Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(image.FileName));
    image.SaveAs(imageFile);

    return View();
}

And in View, you need to include htmlAttribute to upload files.

@using (Html.BeginForm("UploadImage", "Home", 
    FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.LabelFor(x => x.Name)
    @Html.TextBoxFor(x => x.Name)
    @Html.ValidationMessageFor(x => x.Name)

    @Html.LabelFor(x => x.Email)
    @Html.TextBoxFor(x => x.Email)
    @Html.ValidationMessageFor(x => x.Email)

    <input type="file" name="Image" id="Image" />
    <input type="submit" value="Submit" />
}

Make sure the parameter name in the action method and File upload control id is same, otherwise it may not work.

Instead on including the HttpPostedFileBase parameter in the action method, you can also use Request.Files collection. Here is the implementation using Request.Files.

[HttpPost]
public ActionResult UploadImage(Student student, HttpPostedFileBase image)
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        var fileName =
        Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
        file.SaveAs(fileName);
    }

    return View();
}

Happy Programming :)


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe
Archives


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub