Using the following steps you can upload files asynchronously.
We have made use of jquery and Asp.net MVC.
Step 1 : Add the following js files in your project which you can download from the given link.
https://github.com/blueimp/jQuery-File-Upload
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
Step 2 : Following is the HTML code for File control, add that in your Razor (.cshtml) or .aspx file :
<form enctype="multipart/form-data">
<input id="fileupload" name="upload" type="file" /> </form>
Step 3 : Add the following script in the same file you have created file control :
<script type="text/javascript">
function fileUpload(element) {
$(element).fileupload({
dataType: 'json',
url: '/UploadFile/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data is the file data.
// calls the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after successful file upload
},
progress: function (e, data) {
// handle progress
},
fail: function (e, data) {
// handle fail
}
});
};
$(function () {
fileUpload($('#fileupload'));
});
</script>
Step 4 : Add below code in your MVC controller :
[HttpPost]
public JsonResult UploadFile(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}