EasyHostingASP.NET | Best and cheap ASP.NET MVC hosting. In this post we will see how we can upload file without page refresh. As we know, in MVC there is no server controller, this sample will be useful if we want to upload files without page refresh.
If you already know normal file upload, just adding jquery.form.js plugin and few lines of code will do the trick.
In MVC, even html input type “file
” is used to upload files but if we want to upload without page refresh, then either we can use Ajax.BeginForm
or ajax post. There is a jquery plugin called jquery.form.js
which makes the ajax post easy without making it complicated.
Follow these steps to do it.
View Page
Add the required jquery and form library into your page.
1 2 | @section Scripts { <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> |
Html.BeginForm()
.1 2 3 4 5 6 | @using (Html.BeginForm("FileUpload", "Home")) { @Html.AntiForgeryToken() <input type="file" name="files"><br> <input type="submit" value="Upload File to Server"> } |
1 2 | <div class="progress progress-striped"> <div class="progress-bar progress-bar-success">0%</div> |
ajaxForm
to the page. Once user clicks on submit button, post is sent via ajax request instead of http post.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <script> (function () { var bar = $('.progress-bar'); var percent = $('.progress-bar'); var status = $('#status'); $('form').ajaxForm({ beforeSend: function () { status.empty(); var percentVal = '0%'; bar.width(percentVal) percent.html(percentVal); }, uploadProgress: function (event, position, total, percentComplete) { var percentVal = percentComplete + '%'; bar.width(percentVal) percent.html(percentVal); }, success: function () { var percentVal = '100%'; bar.width(percentVal) percent.html(percentVal); }, complete: function (xhr) { status.html(xhr.responseText); } }); })(); </script> |
Action Method
Posted file request will be sent to FileUpload
action method. In MVC, HttpPostedFileBase
class is used to retrieve posted files. Below is the example of FileUplaod
action method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | [HttpPost] [ValidateAntiForgeryToken] public void FileUpload(IEnumerable files) { if (files != null) { foreach (var file in files) { // Verify that the user selected a file if (file != null && file.ContentLength > 0) { // extract only the fielname var fileName = Path.GetFileName(file.FileName); // TODO: need to define destination var path = Path.Combine(Server.MapPath("~/Upload"), fileName); file.SaveAs(path); } } } } |
Note: Input file name (name="files"
) and object of HttpPostedFileBase
in action method parameter should be the same.
- ASPHostPortal vs Site5 – Best Windows ASP.NET Hosting Comparison - September 29, 2017
- Best , Cheap Umbraco 7.7.1 Hosting Recommendation - September 28, 2017
- ASP.NET Web Forms Connection Resiliency and Command Interception - September 27, 2017