0

i made a button that takes an image as an input but i cant find a way to show the picture. i have tried to make an empty element and then change its URL like i saw on a different website but it didnt work.

  • HTML

     <input 
         id="myImage"
         class="photo-upload"
         type="file"
         accept="image/*, image/jpeg">
    
         <img id="the-picture" width="200" />
    
  • JavaScripts

     const uploadPictureButton = document.querySelector(".photo-upload");
    
     uploadPictureButton.addEventListener("click", displayPicture);
    
     function displayPicture(event) {
         let image = document.getElementById("myImage");
         image.src = URL.createObjectURL(event.target.files[0]);
     };
    
  • 3
    This has already been answered. [Link here](https://stackoverflow.com/questions/16500848/how-to-generate-a-thumbnail-image-after-adding-an-image-inside-an-input-type-fi) – dela Sep 14 '20 at 08:37
  • Does this answer your question? [Preview an image before it is uploaded](https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded) – angel.bonev Sep 14 '20 at 08:39

3 Answers3

0

There were some fixes required in the code, the file has to be read and the URL should be created, here is the working snippet for the code.

const uploadPictureButton = document.querySelector(".photo-upload");

  uploadPictureButton.addEventListener('change', function () {
    displayPicture(this);
  });

 function displayPicture(input) {
    if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      document.getElementById('the-picture').setAttribute('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
 }
 <input 
     id="myImage"
     class="photo-upload"
     type="file"
     accept="image/*, image/jpeg">

<img id="the-picture" width="200" /> 
Pratik Singh
  • 167
  • 1
  • 11
  • i tried to run it and it works great! but i dont really understad why, can you please explain to me why did you do the: if(uploadPictureButton) and not just go straight to the function? – Avichai Greenblum Sep 14 '20 at 09:26
  • I removed that, it was not required here, thanks for pointing it out! – Pratik Singh Sep 14 '20 at 13:03
0

You can use innerHTML for display an image also.

0

Try this one out, it works for me

<img height="100" width="100" alt="avatar" id="imgPreview> <input type="file" onchange="document.querySelector("#imgPreview").src = window.URL.createObjectURL(this.files[0])">

Aggestor
  • 55
  • 5