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")
{
$("#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',
type: 'POST',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
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