Pk19000 Pk19000 - 5 months ago 9
HTML Question

Get image by id when preview an image before it is uploaded

I use below script for preview an image before it is uploaded.
I have a html like this:

<div>
<img id="image" src="#">
</div>

<input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(this);">


and js like this:
(I use
jquery-2.0.0.min.js
)

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image').attr('src', e.target.result);
};

reader.readAsDataURL(input.files[0]);
var image = document.getElementById('image');
console.log(image);

}}


My problem is this: when I show image with this script before downloading I can't get image by
var image = document.getElementById('image');
and console log show this:
<img src="#" id="image">
. How I can get image that shown in it before uploading?

Answer

FileReader() .readAsDataURL() method returns results asynchronously. Include var image = document.getElementById('image');console.log(image); or console.log($("#image")[0]) within FileReader onload event handler.

function readURL(input) {
   if (input.files && input.files[0]) {
     var reader = new FileReader();
     reader.onload = function(e) {
       // do stuff when `.readAsDataURL()` complete
       var image = document.getElementById("image");
       image.src = e.target.result;
       console.log(image, e.target.result);
     };
     reader.readAsDataURL(input.files[0]);
   }
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <img id="image" src="#" />
</div>

<input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(this);">