Simple File Uploading Example – ASP.NET MVC 5 for beginners

In this article you will learn
  1. How to Upload a single File into a folder in ASP.NET MVC5?
  2. Simple File Uploading Example
Upload Single File

Most of the time while developing a project you may required to make a panel that allows users to upload file on the server. There are various aspects of uploading a file on to the server like filtering the file, checking the file types and size, save information into the database etc. You will learn all these things in the different article. Here, I am just focusing only on how can you upload a file in a folder with just very simple example.


Step 1: Create a New MVC Project. Open Visual Studio and Go to File > New > Project and select ASP.NET Web Application (.Net Framework).

Step 2: Open Index.cshtml View Page. Go to Solution Explorer > Views > Home > Index.cshtml and write the following code.

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>Simple File Upload ASP.NET MVC</h1>    
</div>

<div class="row">    
    <div class="col-md-4">
       @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
       {
        <input type="file" name="files" />
        <input type="submit" value="OK" />
       }
    </div>    
</div>


Step 3: Open HomeController.cs and write following code.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SimpleFileUpload.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        //Single File Upload
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase files)
        {
            // Verify that the user selected a file
            if (files != null && files.ContentLength > 0)
            {
                // extract only the filename
                var fileName = Path.GetFileName(files.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                files.SaveAs(path);
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index");
        } 
    }
}

Step 4: Create a folder uploads inside App_Data. Right click on App_Data > Add > New Folder.

Create New Folder
Step 5: Build and Run your Project.

Press CTRL + SHIFT + B to build the project and then Press CTRL + F5 to run the project.

Output Single File Upload

Summary

In this programming example, I have explained how can you simply upload a file in a folder using ASP.NET MVC project. This article tells you about single file uploading but in the next article, you will learn how to upload multiple files in ASP.NET MVC with simple programming example.

 

Share your thought