65.9K
CodeProject is changing. Read more.
Home

MVC 4 Ajax File Upload Control - Workaround

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (8 votes)

Mar 20, 2015

CPOL
viewsIcon

32702

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:

<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:

@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:) )

$("#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:

$("#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.

        [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