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?
To display a image selected from file input in React, we can call the URL. createObjectURL with the selected file object to and set the returned value as the value of the src prop of the img element. We define the img state which we use as the value of the src prop of the img element.
First, we have a division element that contains the “img” tag. Using Jquery, we will change the “src” attribute of the “img” tag on upload to preview the image. The second element is the “input” tag. It is essential to specify type = “file” in this context.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With