1

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.

Mahozad
  • 6,430
  • 9
  • 43
  • 70
Abhishek Ekaanth
  • 2,231
  • 2
  • 18
  • 35

1 Answers1

1

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" />
  • addEventListener to detect when a change occurs to the file input
  • Read file's data with readAsDataURL function of the FileReader object

Please read about FileReader and note browser compatability.

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

Community
  • 1
  • 1
roy
  • 97
  • 4