I know, there are many tutorials, but I can't figure out how to make them work.
I have an input form for file upload:
<input onChange="userPreviewImage(this)" type="file" accept="image/*" style="display:none"/>
There is my Javascript code
function userPreviewImage (fileInput) {
    save = true;
    var files = fileInput.files;
    var file = files[0];
    current = file;
    var imageType = /image.*/;
    var img = document.createElement("img");
    img.classList.add("obj");
    img.classList.add("preview");
    img.file = file;
    var reader = new FileReader();
    reader.onload = (function(aImg) { 
        return function(e) { 
            aImg.src = e.target.result; 
        }; 
    })(img);
    reader.readAsDataURL(file);
}
As a result I have img, which is an object <img src="data:image/png;base64..."> which I can print out.
I've been using this for a while, but now I need to change the workflow.
My goal now is instead of printing the image, send its source to the server (the server code is working fine).
I can't figure out how to get the image source from what I have (just the data:image/png;base64... part). Can someone give me a tip?
AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Try posting data URI aImg to server as String
window.onload = function () {
    this.userPreviewImage = function (fileInput) {
        var files = fileInput.files;
        var file = files[0];
        var reader = new FileReader();
        reader.onload = function (aImg) {
            $.post("/echo/html/", {
                html: aImg.target.result
            })
            .then(function (data, textStatus, jqxhr) {
                console.log(data, textStatus);
            }, function(jqxhr, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            })
        };
        reader.readAsDataURL(file);
    }
};
jsfiddle http://jsfiddle.net/8gjb82b6/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With