File upload without page refresh in MVC

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 make the ajax post easily without making it complicated.

If you already know normal file upload just adding jquery.form.js plugin and few lines of code will do the trick.

Follow these steps to do it.

View Page

1. Add required jquery and form library into your page.

@section Scripts {
<script src=""></script>
<script src=""></script>

2. Add file input type inside Html.BeginForm().

@using (Html.BeginForm("FileUpload", "Home"))
<input type="file" name="files"><br>
<input type="submit" value="Upload File to Server">

Showing progress bare: This is optional, you can skip this part if you don’t want to show the progress bar.

<div class="progress progress-striped">
<div class="progress-bar progress-bar-success">0%</div>

3. Add ajaxForm to the page. Once user clicks on submit button post is sent via ajax request instead of HTTP post.

    (function () {
        var bar = $('.progress-bar');
        var percent = $('.progress-bar');
        var status = $('#status');

            beforeSend: function () {
                var percentVal = '0%';
            uploadProgress: function (event, position, total, percentComplete) {
                var percentVal = percentComplete + '%';
            success: function () {
                var percentVal = '100%';
            complete: function (xhr) {


Action Method

Posted file request will be sent to the FileUpload action method. In MVC, HttpPostedFileBase class is used to retrieve posted files. Below is the example of the FileUplaod action method.

        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);

Note: input file name (name=”files”) and object of HttpPostedFileBase in action method parameter should be same.

You can download the sample at GitHub

That’s all. Let me know if you have any question or suggestion.

Leave a Reply

Your email address will not be published. Required fields are marked *