Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC 4 Ajax File Upload Control - Workaround

0.00/5 (No votes)
19 Mar 2015 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here