Last Updated: February 25, 2016
·
32.83K
· andredgusmao

Upload a image using Ajax and FormData

Using this function you can upload a image through the FormData object, available in the XMLHttpRequest Level 2, it uses the same format a form would use if the encoding type were set to "multipart/form-data".

the function search for a input[type=file], and get the data in it. If it's a image creates a FormData object and send the XMLHttpRequest. Once the request is successful, calls a callback function that you can implement.

function upload(callback) {
    //get the input and the file
    var input = document.querySelector('input[type=file]'),
    file = input.files[0];

    //if the file isn't a image nothing happens.
    //you are free to implement a fallback
    if (!file || !file.type.match(/image.*/)) return;

    //Creates the FormData object and attach to a key name "file"
    var fd = new FormData();
    fd.append("file", file);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "URL TO YOUR  FILE HANDLER SERVICE");
    xhr.onloadend = function(e) {
        //The response of de upload
        xhr.responseText;
        if(callback) {
        callback();
    }
}