Home > DeveloperSection > Forums > Upload file using Ajax call using ASP.NET MVC
Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    March-06-2014 10:53 PM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 2168  View(s)
Rate this:

I would like to upload a file in my page using:

<input type="file" name="FileName">

I have a button, clicking on which an ajax post is done.

$.ajax({

           cache: false,

           async: true,

           type: "POST",

           url: '@Url.Content("~/OCR/OCRProcessor")',

           data: '',

           success: function (data) {

               $('#ocrresult').val(data);

           }

       });

I would like to get the file uploaded in the controller action method something like below:

HttpPostedFileBase hpf = Request.Files["FileName"] as HttpPostedFileBase

Please let me know the optimal way to achieve this task.



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-06-2014 11:13 PM

Hi Ankita,

$('#myFormId').submit(function() {

    // submit the form

    $(this).ajaxSubmit();

    // return false to prevent normal browser submit and page navigation

    return false;

});

Demo

This would be a No plugin approach (only in Html5), but I'm still recommending the plugin

$("#myFormId").submit(function(){

    var formData = new FormData($(this)[0]);

    $.ajax({

        url: "YourPath/ToAction",

        type: 'POST',

        data: formData,

        async: false,

        success: function (data) {

            alert(data)

        },

        cache: false,

        contentType: false,

        processData: false

    });

    return false;

});


Don't want to miss updates? Please click the below button!

Follow MindStick