使用HTML5 FileReader将本地图像文件读取到img

时间:2021-12-23 16:32:26

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

我正在尝试将本地图像文件读取为img元素。但readAsDataURL()似乎返回“undefined”。我究竟做错了什么?

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);

2 个解决方案

#1


5  

FileReader.readAsDataURL is asynchronous.

FileReader.readAsDataURL是异步的。

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.

开始读取指定的Blob或文件的内容。当读取操作完成时,readyState将变为DONE,并且将调用onloadend回调(如果有)。那时,result属性包含一个数据:表示文件数据的URL。

Attach an onloadend callback to the reader.

将onloadend回调附加到阅读器。

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

#2


0  

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

#1


5  

FileReader.readAsDataURL is asynchronous.

FileReader.readAsDataURL是异步的。

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.

开始读取指定的Blob或文件的内容。当读取操作完成时,readyState将变为DONE,并且将调用onloadend回调(如果有)。那时,result属性包含一个数据:表示文件数据的URL。

Attach an onloadend callback to the reader.

将onloadend回调附加到阅读器。

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

#2


0  

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