Reputation: 487
I have an ASP.NET MVC 3 application that needs the ability to upload multiple files to the server.
Does Jquery has option of sending the files asynchronusly to action method and saving the same in folder and session variable?
Since I am using this component in many views, should I follow the PRG pattern, or asynchronously upload the file with JQuery?
Upvotes: 1
Views: 4931
Reputation: 2428
Use Jquery file upload pluging.
I usually use plupload.
My Sample To Use PlUpload:
in View:
<div id="file-upload-continer">
<div id="btnInsertFile" style="display: inline-block; width: 100px; border: 1px solid gray;">Choose File</div>
</div>
<table class="file-upload-box">
<tr>
<th>Title</th><th></th><th></th>
</tr>
</table>
<script type="text/javascript">
$(function () {
var uploader = new plupload.Uploader({
url: '@Url.Action("Upload")',
multipart : true,
multipart_params: { },
runtimes: 'html5,html4',
container: 'file-upload-continer',
button_browse_hover : true,
browse_button: 'btnInsertFile'
});
uploader.bind('Init', function (up, params) {
$('.select-document, .file-upload-box').removeClass("hidden");
$('.upload-support').addClass("hidden");
});
uploader.init();
uploader.bind('FilesAdded', function (up, files) {
$.each(files, function (i, file) {
var newRow =
"<tr class='file-row' id='" + file.id + "'>" +
"<td class='title'>" + file.name + " (" + formatFileSize(file.size) + ") </td>" +
"<td class='cancel' id='cancel" + file.id + "'></td>" +
"<td class='status' id='cancel" + file.id + "'></td>" +
"</tr>";
$('.file-upload-box').append(newRow);
//Bind cancel click event
$('#cancel'+file.id).click(function(){
$('#' + file.id).remove();
uploader.removeFile(file);
$(this).unbind().remove();
});
});
uploader.start();
});
uploader.bind('BeforeUpload', function (up, file) {
$(".status", ".file-row#" + file.id).addClass('throbber');
});
uploader.bind('FileUploaded', function (up, file) {
$(".throbber", ".file-row#" + file.id).addClass('success').removeClass('throbber');
$(".cancel", ".file-row#" + file.id).removeClass('cancel');
});
uploader.bind('Error', function (up, err) {
$(".throbber", ".file-row#" + err.file.id).addClass('error').removeClass('throbber');
$(".cancel", ".file-row#" + err.file.id).removeClass('cancel');
});
});
</script>
and in My Controller:
public ActionResult Upload(string name = "", int chunk = 0)
{
if (Request.Files.Count < 1)
return Json(false);
HttpPostedFileBase fileUpload = Request.Files[0];
// Save file
return Json(true, "text/html");
}
Upvotes: 2
Reputation: 2333
If you would like to use jQuery to upload your files, i will recommend you this library:
It can upload multiple files asynchronusly. There are enough examples on their website.
http://www.uploadify.com/demos/
Upvotes: 0