永远不会触发FileReader的onloadend事件

时间:2015-10-22 15:13:39

标签: javascript jquery

我尝试制作一个小片段,以便在上传之前预览图片:

$.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);
}
};

我称之为:

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

但永远不会调用onloadend函数。 FIDDLE

1 个答案:

答案 0 :(得分:0)

实际上,您必须指定文件并指示fileReader读取它。

以下是更正后的代码。

$.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"));