15

I am trying to show the client an image which he has selected:

<input type="file" onchange="showImage(this)"/>

But I can't read the value of the input, as I checked out here. Is it possible to display the image?

In onchange I can send the form to server and server can send the data back, but is it really necessary? Can't the client display the data without the ping-pong to the server? Is it a security issue?

Community
  • 1
  • 1
revolver
  • 307
  • 1
  • 2
  • 8
  • If you're submitting a form this way then yes - the ping-pong to the server is unavoidable. You could load the image from the local file system with the HTML5 File API and display it. –  Jun 16 '13 at 22:23

1 Answers1

33

You can use FileReader web-api object for this, see this snippet:

the HTML

<input id="src" type="file"/> <!-- input you want to read from (src) -->
<img id="target"/> <!-- image you want to display it (target) -->

the javascript

function showImage(src,target) {
  var fr=new FileReader();
  // when image is loaded, set the src of the image where you want to display it
  fr.onload = function(e) { target.src = this.result; };
  src.addEventListener("change",function() {
    // fill fr with image data    
    fr.readAsDataURL(src.files[0]);
  });
}

var src = document.getElementById("src");
var target = document.getElementById("target");
showImage(src,target);
Morteza
  • 63
  • 1
  • 12
Jan Turoň
  • 26,696
  • 21
  • 102
  • 153