htmlthymeleafimage-uploadinglive-preview

Live preview of the uploaded image in thymeleaf


Here, I'm stuck in displaying preview of the uploaded picture as soon as it is uploaded. All I have done is to get the image upload button:

<div class="form-group">
  <label for="recipientName">Image Upload</label>
  <input type="file" name="file"/>
</div>

After this, I'm not familiar how to proceed.


Solution

  • var reader = new FileReader();
    reader.onload = function(r_event) {
      document.getElementById('prev').setAttribute('src', r_event.target.result);
    }
    
    document.getElementsByName('file')[0].addEventListener('change', function(event) {
        reader.readAsDataURL(this.files[0]);
    });
    <input type="file" name="file" />
    <img src="" id="prev" />

    Please read about FileReader and note browser compatability.

    Check out this topic -> Preview an image before it is uploaded