Click here to Skip to main content
15,903,388 members
Articles / Programming Languages / C# 4.0
Tip/Trick

MVC 4 Ajax File Upload Control - Workaround

Rate me:
Please Sign up or sign in to vote.
4.60/5 (8 votes)
19 Mar 2015CPOL 32.4K   11   1
MVC 4 Ajax File Upload Control - Workaround

Introduction

Though there are many good file upload controls available for MVC Ajax application, most of them are not free, so if you want to use file Upload in MVC Ajax application where you are not periodically uploading files and files are small in size, you can do the following workaround to make it work:

HTML
<div id="divUploadFileAdd">
<form enctype="multipart/form-data" id="frmUplaodFileAdd">

  @Html.AntiForgeryToken()
  <input id="fuPDFAdd" name="file" type="file" /> 
  <input class="gbtn" id="btnUploadAdd" type="button" value="Upload" />
  <label id="txtuploadedMsgAdd"> </label>

</form>
</div>

In MVC razor view, keep the file upload control outside of Ajax form:
Rest of the form might be:

JavaScript
@using (Ajax.BeginForm("AddTemp", "temp", new AjaxOptions

{ HttpMethod = "post", LoadingElementId = "overlayTemp",
OnSuccess = "SuccessTemp", OnFailure = "AjaxRequestError" },
new { id = "AddTempForm" }))
{}

In JavaScript, we need to capture the onchange event of file upload control and make the callback to MVC action to store our file in server variable like session. (This code is taken from someone's article, I will update the URL once I will find it:) )

JavaScript
$("#fuPDFAdd").change(function () {
        var file = this.files[0];
        fileName = file.name;
        size = file.size;
        type = file.type;
        if (type.toLowerCase() == "application/pdf")
       { //I just want pdf files and only want to show
        //upload button if it is of my desired type
            $("#txtuploadedMsgAdd").text("");
            $("#btnUploadAdd").show();
        }
        else {
            $("#txtuploadedMsgAdd").text("Error: Please select pdf file.");
            $("#btnUploadAdd").hide();
            $("#divAddInforamtionDialog").hide();
        }
      });

Following is the button upload control:

JavaScript
$("#btnUploadAdd").click(function () {

        var formData = new FormData($('#frmUplaodFileAdd')[0]);
        $.ajax({
            url: '/Control/UploadFile',  //Server script to process data
            type: 'POST',
            xhr: function () {  // Custom XMLHttpRequest
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) { // Check if upload property exists
                    myXhr.upload.addEventListener('progress',
                    progressHandlingFunction, false); // For handling the progress of the upload
                }
                return myXhr;
            },
            data: formData,
            //Options to tell jQuery not to process data or worry about content-type.
            cache: false,
            contentType: false,
            processData: false
        });
    });

//If file is successfully uploaded, label is updated with message
    function progressHandlingFunction(e) {
        if (e.lengthComputable) {
            $("#divAddInforamtionDialog").show();
            $("#txtuploadedMsgAdd").text("  " + fileName + " uploaded successfully");
        }
    }

In Controller Action, I am storing this file in session to use it further in application.

C#
[HttpPost]
public void UploadFile(HttpPostedFileBase file)
{
    BRSessionObj.UplaodFile = file;
}

Again, this is just a workaround, if you are developing an application that requires uploading of a lot of files, I would suggest to take money out of your pocket and buy a good control.

History

  • 3/19/2015: Created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
A Solutions Architect with more than fourteen years of experience in application development. I mostly work in .NET, Angular, MEAN stack technologies and love to share what I do and learn during my day to day job. Please check my tutorials and blog:
https://fullstackhub.io
https://fullstackhubblog.com

Comments and Discussions

 
QuestionGood work around Pin
M AZZAAAM24-Mar-15 0:25
M AZZAAAM24-Mar-15 0:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.