Reputation: 12045
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
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
Reputation: 360026
FileReader.readAsDataURL
is asynchronous.
Starts reading the contents of the specified
Blob
orFile
. When the read operation is finished, thereadyState
will becomeDONE
, and theonloadend
callback, if any, will be called. At that time, theresult
attribute contains adata:
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