Flash Thunder
Flash Thunder

Reputation: 12045

Read local image file to img using HTML5 FileReader

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

Upvotes: 3

Views: 8637

Answers (2)

Mariano E. Ferro
Mariano E. Ferro

Reputation: 1

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

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360026

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

Upvotes: 6

Related Questions