简体   繁体   中英

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>

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

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

尝试

<input type="file" id="fileinput" />

获取文件..您可以使用

var myFile = $('#fileinput').prop('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