Szabolcs
Szabolcs

Reputation: 1533

FileReader's onloadend event is never triggered

I'm trying to make a small snippet to preview images before uploading them:

$.fn.previewImg=function($on){
var input = this;

try{
    if (this.is("input[type='file']")) {
        input.change(function(){
            var reader = new FileReader();

            reader.onloadend = function(){
                for (var i = 0; i < $on.length; i++) {
                    if (/img/i.test($on[i].tagName)) $on[i].src = reader.result;
                    else $on[i].style.bakgroundImage = "url("+reader.result+")";
                }
            };
        });
    }else throw new exception("Trying to preview image from an element that is not a file input!");
}catch(x){
    console.log(x);
}
};

I'm calling it like:

$("#file").previewImg($(".preview_img"));

but the onloadend function is never called. FIDDLE

Upvotes: 1

Views: 1116

Answers (1)

prasun
prasun

Reputation: 7343

Actually , you got to specify the file and instruct the fileReader to read it.

Below is the corrected code.

$.fn.previewImg=function($on){
    var input = this;

    try{
        if (this.is("input[type='file']")) {

            input.change(function(evt){

                var reader = new FileReader();
                console.log("Input changed");

                reader.onloadend = function(){
                    console.log("onloadend triggered");
                    for (var i = 0; i < $on.length; i++) {
                        if (/img/i.test($on[i].tagName)) $on[i].src = reader.result;
                        else $on[i].style.bakgroundImage = "url("+reader.result+")";
                    }
                };
               //get the selected file
                var files = evt.target.files; 
                //instruct reader to read it
                reader.readAsDataURL(files[0]);
            });
        }else throw new exception("Trying to preview image from an element that is not a file input!");
    }catch(x){
        console.log(x);
    }
};

$("#file").previewImg($(".preview_img"));

Upvotes: 1

Related Questions