How to upload file on mvc ?


So many time, beginner in mvc will ask this question. I will show on basic demo for this functionality.

Step 1: Create the Index view like this

    ViewBag.Title = "Index";

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" /><br><br>
    <input type="submit" value="Upload Image" />

Step 2: Write the code in Home Controller for file upload like this

using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace ImageUpload_MVC.Controllers
    public class HomeController : Controller
        // GET: Home
        public ActionResult Index()
            return View();

        public ActionResult FileUpload(HttpPostedFileBase file) 
            if (file != null && file.ContentLength > 0)
                    string path = Path.Combine(Server.MapPath("~/Images"),
                    ViewBag.Message = "File uploaded successfully";
                catch (Exception ex)
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                ViewBag.Message = "You have not specified a file.";
            return View("Index");
            //return RedirectToAction("Index", "Home");

Note: Don’t forget to keep Images folder in application


We show the basic file upload functionality in MVC.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.