Read local image file to img using HTML5 FileReader

梦想的初衷 提交于 2019-12-10 22:24:57

问题


I am trying to read local image file to img element. But readAsDataURL() seems to return "undefined". What am I doing wrong?

var input = $('.mapimage_input').get(0);
console.log(input); // <input type="file" class="mapimage_input" accept="image/jpeg">
var file = input.files[0];
console.log(file); // File {webkitRelativePath: "", lastModifiedDate: Fri Mar 30 2012 12:32:03 GMT+0200, name: "avatar.jpg", type: "image/jpeg", size: 8724…}
var fr = new FileReader();
var img = fr.readAsDataURL(file);
console.log(img); // undefined
$('.mapimage_layer').attr('src',img);

回答1:


FileReader.readAsDataURL is asynchronous.

Starts reading the contents of the specified Blob or File. When the read operation is finished, the readyState will become DONE, and the onloadend callback, if any, will be called. At that time, the result attribute contains a data: URL representing the file's data.

Attach an onloadend callback to the reader.

fr.onloadend = function() {
    var img = fr.result;                
    console.log(img);
    $('.mapimage_layer').attr('src',img);
}



回答2:


this works fine to me!!

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery('#target').attr('src', e.target.result);

        }

        reader.readAsDataURL(input.files[0]);
    }
}

jQuery("#inputTypeFile").change(function(){
    readURL(this);
});


来源:https://stackoverflow.com/questions/18493869/read-local-image-file-to-img-using-html5-filereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!