How to display selected image without sending data to server?

前端 未结 1 408
刺人心
刺人心 2020-11-28 13:00

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


But I can\'t read

相关标签:
1条回答
  • 2020-11-28 13:23

    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);
    
    0 讨论(0)
提交回复
热议问题