Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

jquery Forms plugin would be an ideal choice in this context. You can simply do it like this. (Include the file input in this form)

$('#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;
});

Another nice plugin.

share|improve this answer
    
Can you suggest any way to do this without using jquery Plugin. –  Shanky Mar 4 at 8:38
    
Why without plugin? –  Subin Jacob Mar 4 at 8:39
    
I would like to know if it can be achieved just by using the .ajax() –  Shanky Mar 4 at 8:41
    
using html5 formdata object you can do it. This jQuery plugin is also doing the same. But it has its own fall back mechanism if Html5 is not supported –  Subin Jacob Mar 4 at 8:44
    
i will try that. But please let me know if any other ways are there to achieve this. –  Shanky Mar 4 at 8:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.