Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX - How to get data from input file to append formdata?

Hello I want to use pure javascript ajax (no jquery) to append formdata but I don't know how to get data from input file type

function handleForm(e) 
{
    e.preventDefault();
    var username = document.getElementById('username').value;
    var email = document.getElementById('email').value;

    var data = new FormData();

    data.append('username', username); 
    data.append('email', email);
    data.append('file', ?????);  ////// How to get data from input file


    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'test2.php', true);

    xhr.onload = function(e) {
        if(this.status == 200) {
            console.log(e.currentTarget.responseText);  
            alert(e.currentTarget.responseText + ' items uploaded.');

        }
    }

    xhr.send(data);
}

...

    Username: <input type="text" name="username" id="username"><br/>
    Email: <input type="text" name="email" id="email"><br/>
    Image: <input type="file" name="file" id="myimg"><br/>

    <input type="submit">
</form>
like image 892
doflamingo Avatar asked Dec 29 '16 12:12

doflamingo


2 Answers

The <input type="file" /> HTML element has a files property (of type FileList).
Check the length if a file has been selected and if so add the file(s) to the FormData object

var fileInput = document.getElementById("myimg");
if (fileInput.files.length > 0) {
    data.append("file", fileInput.files[0]);
}

For more examples on how to use the FormData object check this link: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

like image 129
Andreas Avatar answered Sep 19 '22 23:09

Andreas


document.getElementById("file_input_id").files[0]

try

like image 36
Unamed Avatar answered Sep 21 '22 23:09

Unamed