问题
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
BloborFile. When the read operation is finished, thereadyStatewill becomeDONE, and theonloadendcallback, if any, will be called. At that time, theresultattribute 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);
}
回答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