Juliver Galleto
Juliver Galleto

Reputation: 9037

get the selected file from the input file

I'm trying to put the selected file from the input file to the newly created 'formData' on form submit, below is what I have tried.

first I have the form

<form action="/upload.php">
    <fieldset>
        <input type="file" name="file">
        <input type="text" name="full_name">
    </fieldset>
    <button>SEND</button>
</form>

and then the script

$(document).ready(function(){
    $("form").submit(function(e){
        e.preventDefault();
        var dis = $(this),fdata = new FormData();
        fdata.append('file',dis.find('input[type="file"]').files[0]);
        fdata.append('full_name',dis.find('input[name="full_name"]').val());
    });
});

but it gives me this error

Uncaught TypeError: Cannot read property '0' of undefined

Any help, ideas please?

Upvotes: 0

Views: 65

Answers (2)

Satpal
Satpal

Reputation: 133403

Since dis.find('input[type="file"]') returns jQuery object and they don't have files property thus you are getting the error, You need to get the underlying DOM element then access the property. So use

dis.find('input[type="file"]')[0].files[0]

instead of

dis.find('input[type="file"]').files[0]

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

FormData accepts as input the form element

Try the following

fdata = new FormData($(this)[0]);

remove the append

Upvotes: 1

Related Questions