简体   繁体   中英

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?

FormData accepts as input the form element

Try the following

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

remove the append

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM