Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display selected image without sending data to server?

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?

like image 281
revolver Avatar asked Jun 16 '13 22:06

revolver


People also ask

How do I show selected images in react?

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.

How do you preview an image before it is uploaded using jquery?

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.


1 Answers

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);
like image 169
Jan Turoň Avatar answered Oct 16 '22 20:10

Jan Turoň