4

Now I have a form field:

<input id="my_img_field" type="file"/>

After I select the image in the browser, I want to render the selected image file on the target img tag:

<img id="image_preview" />

But I want to do this after the $('#my_img_field').change event, i.e. I may want this done when I click some button later.

I heard that this could be done using HTML5 technique. Can someone teach me how?

2

3 Answers 3

6

the code in vanilla js

var file = document.getElementById('my_img_field').files[0]
    var fr = new FileReader()
    fr.readAsDataURL(file)
    fr.onload = function(e) {
      var img = document.getElementById('image_preview')
      img.src = this.result
    } 
4

The following approach will work:

var file = $('#my_img_field')[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
    var img = $('#image_preview');
    img.attr('src', this.result);
}
2

It can be like this

const file = document.getElementById('my_img_field').files[0]
const link = window.URL.createObjectURL(file)

Not the answer you're looking for? Browse other questions tagged or ask your own question.