How to Upload an Image File in ASP.NET MVC 4

In this post, I'm sharing a code snippets on how to upload an image file in ASP.NET MVC. In the cshtml file you must prepare the submit form by setting the type to post and the enctype to multipart as per the following syntax:

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

The name of the input file should match the parameter name that you will use in the server side action.

Here is the server side code of the upload action:

public class UploadController : BaseController
{
    public ActionResult UploadDocument()
    {
        return View();
    }

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

        return RedirectToAction("UploadDocument");
    }
}

Also, you can find the file in the Request.Files, as per the following code example:

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);
    }
}

Share your code if you have a better way of uploading an image in ASP.NET MVC 4

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website