2

The image file name is 'default.jpg']

I want that when the button for change picture is clicked an input type=file opens up and as soon as the image is selected the image src is updated. How can I achieve this? I am using PHP as the server side language and trying to do on web page.

Ayush Bansal
  • 49
  • 2
  • 9
  • 1
    Some code to show of what you've tried so far...? – Anna Jan 14 '17 at 17:30
  • 1
    Not enough information. For example: are you trying to do it in web? What server side tech. are you using (PHP, Node.js etc.)? Or is it an HTML/JavaScript based desktop / mobile app? Nothing is clear from your question. – Fayaz Jan 14 '17 at 17:32
  • I haven't tried anything. I know how to show input type=file on clicking of button but I have no idea how to update the img as soon as file is chosen. – Ayush Bansal Jan 14 '17 at 17:35
  • 1
    Read the file using [FileReader API](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) and `.readAsDataURL` method. Then use the value returned by the said method as `src` of an image. – Teemu Jan 14 '17 at 17:35
  • Simplest solution: https://stackoverflow.com/a/56777541/8240417 – Arif Oct 27 '19 at 18:27

2 Answers2

5

You can doit using HTML5 FileReader. You don't need to use PHP or server side for that.

See this JSFidlle: https://jsfiddle.net/166p3uqk/1/

You don't need a FORM or value to your INPUT text.

HTML:

<input onchange=file_changed() type=file id=input>
<img id=img>

Javascript:

function file_changed(){
  var selectedFile = document.getElementById('input').files[0];
  var img = document.getElementById('img')

  var reader = new FileReader();
  reader.onload = function(){
     img.src = this.result
  }
  reader.readAsDataURL(selectedFile);
 }

More info:

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
1

Don't know if you need the image to be uploaded to server first or not But just for front-end it could be done by:

<input type="file" class="changeimage" id="changeimage" accept="image/*"/>
<img class="image" src="default.png" style="height:120px"/>
<script>
    document.getElementById("changeimage").addEventListener("change", function(){
        var reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById("image").setAttribute('src', e.target.result);
        }

    });
</script>

You can also find a solution at onchange file input change img src and change image color

Good Luck:)

Community
  • 1
  • 1