Vahid Akbari
Vahid Akbari

Reputation: 189

send file with jquery post without page refresh mvc

I want to post File by AJAX post with jQuery without page refresh, but I have a problem.

I get this error in jquery: Uncaught TypeError: Illegal invocation

HTML

<table id="tblQuadrupletRange" >***

    <tr>
        <td >
            <input id="QuadrupletRangeFile" name="QuadrupletRangeFile" type="file" /></td>
    </tr>
    <tr>
        <td colspan="7">
            <a href="#" id="InsertQR">Insert</a>
        </td>
    </tr>
</table>

Javascript

<script type="text/javascript" src="../../Scripts/jquery-1.10.2.min.js"></script>
$(document).on('click', "#InsertQR", function (e) {
    var url = '@Url.Action("SetQuadrupletRangeList")';

    var photo = document.getElementById("QuadrupletRangeFile");
    var file = photo.files[0];
    $.post(url, { file:file }, function (data) {
        if (data == "True") {
            //do something
        }
    });}
);

Controller C# code

[HttpPost]
public void SetQuadrupletRangeList( HttpPostedFileBase file)
{    
    HttpPostedFileBase objpostFile = file;  
}

Upvotes: 2

Views: 2138

Answers (2)

Borys Generalov
Borys Generalov

Reputation: 2345

The post must be replaced with ajax call and be updated as follows:

data = new FormData();
data.append('file', file);
$.ajax({
    url: url,
    data: data,
    enctype: 'multipart/form-data',
    processData: false,  // do not process the data as url encoded params
    contentType: false   // by default jQuery sets this to urlencoded string
    type: 'POST',
    success: function ( data ) {
       alert( data );
    }
});

From jQuery docs:

processData (default: true) Type: Boolean By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

Upvotes: 3

Borys Generalov
Borys Generalov

Reputation: 2345

How about your form encoding type, is it enctype = "multipart/form-data"?

Upvotes: 1

Related Questions