Client side:
1. Get the latest lib from http://valums.com/ajax-upload
2. Copy into your project
3. Add refrence in your aspx file:
<script src='<%=Page.ResolveClientUrl("~/Scripts/ajaxupload.3.6.js")%>' type="text/javascript"></script>
4. Add Javascript code to call ajaxupload
<script type="text/javascript">
$(document).ready(function() {
var button = $('#upload')[0], interval;
new AjaxUpload(button, {
action: '<%= Url.Relative("~/ControllerName/Save") %>',
name: 'myfile',
onSubmit: function(file, ext) {
if (!(ext && /^(doc|pdf|txt|xls)$/.test(ext))) {
alert('Error: invalid file extension');
return false;
}
button.value = 'Uploading';
this.disable();
interval = window.setInterval(function() {
var text = button.value;
if (text.length < 13) {
button.value = button.value + '.';
} else {
button.value = 'Uploading';
}
}, 200);
},
onComplete: function(file, response) {
button.value = 'Upload';
window.clearInterval(interval);
this.enable();
if (response == 'error')
alert('Error: File size is over limit (10mb). '+file);
else
//Dispaly uploaded file
},
responseType:'json'
});
});
</script>
Server side is very simple. Just create a Json action:
public JsonResult Save()
{
try
{
var files = this.HttpContext.Request.Files;
string filename = System.IO.Path.GetFileName(files[0].FileName);
files[0].SaveAs(filename);
return Json(null);
}
catch
{
return Json("error");
}
}
No comments:
Post a Comment