How to display the selected image without sending data to the server?

I am trying to show the client the image that he selected:

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

But I can not read the value of the input, as I checked here . Can I display an image?

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

+6
source share
1 answer

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

HTML

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

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); 
+13
source

Source: https://habr.com/ru/post/947421/


All Articles