Hello Friends, In this tutorial, I am going to create an example for how to Upload File in ASP.NET MVC.

Introduction:

Upload File is an important task for every application. In this tutorial, I am going to create an example for Uploading File. The posted file is available as HTTPPostedFileBase.

Upload File

Upload File in ASP.NET MVC.

Step 1- Open visual studio and create an MVC4 application called  UploadFileDemo,

Upload File

Step 2- Choose an empty template and Click OK. An empty solution will be completed.

Step 3- Right Click on the Controllers folder and Create a Controller called HomeController. A Controller with the following code will be created.

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

namespace UploadFileDemo.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
return View();
}

}

}

Step 4- Right Click on the Index action method and Add a View called Index.

Step 5- Write the following code into Index.cshtml.



<h2>Upload File</h2>


<h3 style="color:green">@ViewBag.Message</h3>


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

<fieldset>

<legend>Registration Form</legend>


<ol>
            

<li class="lifile">
                <input type="file" id="txtFileUpload" name="file" />
                <span class="field-validation-error" id="spanfile"></span>
            </li>


        </ol>


        <input type="submit" id="btnSubmit" value="Upload" />
    </fieldset>


}

Step 6- Right Click on the Solution Explorer and create a folder called Scripts.

Step 7- Add the following Scripts in the Scripts folder that we have created in Step 6.

  • jquery-1.7.1.min.js.
  • jquery.validate.min.js.
  • jquery.validate.unobtrusive.min.js.

Step 8- Right Click on the Scripts folder and Create a JavaScript file called App.Js. Write the following code in App.js.

function GetFileSize(fileid) {
try {
var fileSize = 0;
//for IE
if ($.browser.msie) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in kb
fileSize = fileSize / 1048576; //size in mb
}

// alert("Uploaded File Size is" + fileSize + "MB");
return fileSize;
}
catch (e) {
alert("Error is :" + e);
}
}

//get file path from client system
function getNameFromPath(strFilepath) {

var objRE = new RegExp(/([^\/\\]+)$/);
var strName = objRE.exec(strFilepath);

if (strName == null) {
return null;
}
else {
return strName[0];
}

}

$("#btnSubmit").live("click", function () {

if ($('#txtFileUpload').val() == "") {
$("#spanfile").html("Please upload file");
return false;
}
else {
return checkfile();
}
});

function checkfile() {
var file = getNameFromPath($("#txtFileUpload").val());
if (file != null) {
var extension = file.substr((file.lastIndexOf('.') + 1));
// alert(extension);
switch (extension) {
case 'jpg':
case 'png':
case 'gif':
case 'pdf':
flag = true;
break;
default:
flag = false;
}
}
if (flag == false) {
$("#spanfile").text("You can upload only jpg,png,gif,pdf extension file");
return false;

}
else {
var size = GetFileSize('txtFileUpload');
if (size &amp;amp;amp;gt; 3) {
$("#spanfile").text("You can upload file up to 3 MB");
return false;
}
else {
$("#spanfile").text("");
}
}
}
$(function () {
$("#txtFileUpload").change(function () {
checkfile();
});

});

Step 9- Now the complete code for the View would be.

@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/App.js"></script>
<h2>Upload File</h2>


<h3 style="color:green">@ViewBag.Message</h3>



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


<fieldset>

<legend>Registration Form</legend>


<ol>
            


<li class="lifile">
                <input type="file" id="txtFileUpload" name="file" />
                <span class="field-validation-error" id="spanfile"></span>
            </li>



        </ol>



        <input type="submit" id="btnSubmit" value="Upload" />
    </fieldset>



}}

Step 10-  Right Click on the Solution Explorer and create a folder Content.

Step 11- Goto HomeController and write the following method in HomeController.

    [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file == null)
                {
                    ModelState.AddModelError("File", "Please Upload Your file");
                }
                else if (file.ContentLength &gt; 0)
                {
                    int MaxContentLength = 1024 * 1024 * 3; //3 MB
                    string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };

                    if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                    {
                        ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                    }

                    else if (file.ContentLength &gt; MaxContentLength)
                    {
                        ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                    }
                    else
                    {
                        //TO:DO
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/Content"), fileName);
                        file.SaveAs(path);
                        ModelState.Clear();
                        ViewBag.Message = "File uploaded successfully";
                    }
                }
            }
            return View();
        }

Run the application and look at the output screen.

Upload File

You can download the complete Source Code for the application from here.

Conclusion:

Hope you understand this tutorial about Uploading File in ASP.NET MVC. I will appreciate your feedback, comments and suggestions.

View More:

Thank You.

One Thought to “How to upload file in in ASP.NET MVC”

  1. I have been browsing online more than 3 hours
    today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. In my opinion, if all web owners and bloggers made
    good content as you did, the net will be much more useful than ever before.

     

Leave a Comment