Ajax.BeginForm in MVC to upload files Ajax.BeginForm in MVC to upload files ajax ajax

Ajax.BeginForm in MVC to upload files


That is complicated better use jquery forms plugin.

Here is the sample:

Html.BeginForm

 @using (Html.BeginForm("YourAction", "YourController")){    @Html.AntiForgeryToken()    <input type="file" name="files"><br>    <input type="submit" value="Upload File to Server">}

Action Method

    [HttpPost]    [ValidateAntiForgeryToken]    public void YourAction(IEnumerable<HttpPostedFileBase> 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);                }            }        }    }

Progress Bar

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

Jquery & Form script

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script><script src="http://malsup.github.com/jquery.form.js"></script><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>

Update...

People who are getting issue of calling action method twice is due to Ajax.BeginForm, just convert it to Html.BeginForm(). For more clarification and to download sample code please refer at this blog.


The answer from Ashwini Verma is almost correct but it has a drawback, the form is submitted twice.

This is caused by the use of Ajax.BeginForm(). Using Html.BeginForm() will fix it.

Here's an example:

@* do not use Ajax.BeginForm() as it would cause the form to submit twice in connection with jQuery.Form *@@using (var lForm = Html.BeginForm(   <ActionName>, <ControllerName>, FormMethod.Post,   new Dictionary<string, object> {{"name", <YourFormName>}, {"enctype", "multipart/form-data"}})){


You need html5 file handling and read file contents on client to get base64 encoded data.

On client you have to put:

<div>        @Html.HiddenFor(m => m.AttachmentFileName)        @Html.HiddenFor(m => m.AttachmentFileSize)        @Html.HiddenFor(m => m.AttachmentFileType)        @Html.HiddenFor(m => m.AttachmentFileContentsBase64)    <input type="file" name="AttachmentFile" id="AttachmentFile" onchange="handleAttachmentFileChange(this.files)" />    @Html.ValidationMessageFor(m => m.AttachmentFile)</div><script>    function handleAttachmentFileChange(files) {        var file = files[0];        $("#AttachmentFileName").val(file.name);        $("#AttachmentFileSize").val(file.size);        $("#AttachmentFileType").val(file.type || "application/octet-stream");        var fileReader = new FileReader();        fileReader.onload = function () {            fileReader.result;            $("#AttachmentFileContentsBase64").val(fileReader.result);        };        fileReader.readAsDataURL(file);    };</script>

So your code will fill hidden fields with file data (filename, type, size, base64 encoded contents).And on server side you put:

            if (AttachmentFileSize > 0)            {                string fileName = AttachmentFileName.Contains("\\") ? AttachmentFileName.Substring(AttachmentFileName.LastIndexOf("\\") + 1) : AttachmentFileName;                byte[] fileBytes = Convert.FromBase64String(AttachmentFileContentsBase64.Substring(AttachmentFileContentsBase64.IndexOf(',') + 1));//save file to file system or db                ModelState.Remove("CurrentAttachmentFileId");                ModelState.Remove("CurrentAttachmentFileName");            }            else if (AttachmentFileSize == -1)            {//remove existing file from fs or db            }

The code needs to be modified with your models and logic but it worked for me