Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload with ajax

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?

like image 635
user3078775 Avatar asked May 02 '15 07:05

user3078775


People also ask

What is AJAX in JavaScript with example?

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.


1 Answers

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/

like image 116
guest271314 Avatar answered Oct 07 '22 04:10

guest271314