Web Programming TutorialsLearn to Upload a file in MVC via Ajax

Learn to Upload a file in MVC via Ajax


HI friends, today we are going to learn how to save a file in MVC.

File Upload in MVC
In asp.net, we use the control mentioned below to save a file to the server


But in MVC there are no asp.net controls, so basically we use normal control like below one and post it to the controller.

<input type="file">

Which Means Loading a file in Asp.Net MVC application is very simple. The posted file is automatically available as HttpPostedFileBase parameters in the action of the control. To upload a file on the server we require a file input control in html form with enctype set to multipart/form-data.

So let’s start with the example. We are using Ajax post and get method in below example.

Open visual studio then click on file new project select asp.net MVC web application select Internet Application.
Java Programming Course for Beginner From Scratch
Now Open Index.cshtml inside ViewHome Folder and replace all the code in the folder with the code shown below.

<h1>Http get and post</h1>

<div class="clear">  <br /> </div>
<form action="" method="post" enctype="multipart/form-data">
  <label>Upload File:</label>
    <input type="file" name="file" id="file" />
    <input type="submit" id="submitbtn" />


Now open HomeController file, inside the Controllers folder and add the code below in it. Also create a UploadFile folder in the root directory.

       // use IEnumerable<HttpPostedFileBase> files if you want to post multiple files
        public ActionResult Index(HttpPostedFileBase file)
            if (file.ContentLength > 0)
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/UploadFile/"), fileName);
            return RedirectToAction("Index");


Now run the application and see the output.


Summary: In above example we have learned how to post a file in MVC.

File Upload in MVC via ajax
Now if you want to save the file using Ajax, put the below code in index view. In this we have used Jquery Ajax request to save the file in server. Don’t forget to add Jquery lib reference.

<h1>Post File to Controller</h1>
<div class="clear"><br /></div>
<form method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <input type="submit" id="submitbtn" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $(function () {
        $('#submitbtn').click(function () {
            var data = new FormData();
            var files = $("#file").get(0).files;

            if (files.length > 0) { data.append("HelpSectionImages", files[0]); }
            else {
                common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
                return false;
            var extension = $("#file").val().split('.').pop().toUpperCase();
            if (extension != "PNG" && extension != "JPG" && extension != "GIF" && extension != "JPEG") {
                common.showNotification('warning', 'Imvalid image file format.', 'top', 'right');
                return false;
                url: '../home/SaveProfileImage', type: "POST", processData: false,
                data: data, dataType: 'json',
                contentType: false,
                success: function (response) {
                    if (response != null || response != '')
                error: function (er) { }

            return false;


Learn HTML5 Programming For Beginners
Now Open Home Controller and paste the code shown below.

        public ActionResult SaveProfileImage()
                if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
                    var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
                    HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
                    var fileName = Path.GetFileName(filebase.FileName);
                    var path = Path.Combine(Server.MapPath("~/UploadFile/"), fileName);
                    return Json("File Saved Successfully.");
                else { return Json("No File Saved."); }
            catch (Exception ex) { return Json("Error While Saving."); }

Now run the application and see the result.
Summary: In above example we have learnt how to post a file in MVC via ajax post.


  1. I am using File upload with Ajax, i am getting the “System.Web.HttpContext.Current.Request.Files” is zero. Any idea?


Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -Newspaper WordPress Theme

Latest article


More article

- Advertisement -Newspaper WordPress Theme