How to upload file on asp.net mvc ?


FileUpload

So many time, beginner in asp.net 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" />
    <br><br>
    @ViewBag.Message
}

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

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase file) 
        {
            if (file != null && file.ContentLength > 0)
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Images"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            else
            {
                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

Summary:

We show the basic file upload functionality in asp.net MVC.

Advertisement

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.