Search code examples
jqueryformsfile-uploadform-data

how can I Send File via jQuery?


I want send a file via JQuery

I create a form like this:

<form id="form">
<input type="text">
<input type="file">
</form>

and I use this Jquery code to send data.

    var datastring = $("#form").serialize();

    $.ajax({
        type: "POST",
        url: "function/formRegister",
        data: datastring,
        async: true,
        dataType: 'json',
        success: function(data)
        {
        }

I can send input.text value to server But I can not send input.file

I know I must FormData. how can I use it?


Solution

  • Instead of serialize try FormData

    var datastring = new FormData($("#form")[0]);
    

    Add this in your ajax to tell dont worry about content & dont process data

    cache: false,
    contentType: false,
    processData: false