Search code examples
image-processinggoogle-chromefile-uploaduploading

Image Upload preview not working Chrome


This is code only Compatibility IE, FF but not working chrome and safari. please suggest me a way for that.

<h3>Choose an image:</h3>   
    <input type='file'  onchange="document.images[0].src=getPath(this);"  />


<h3>preview</h3>    
    <img src="#" alt="your image"    /> 

<script type='text/javascript'>

function getPath(input){
   if(input.files && input.files[0]){
      return input.files[0].getAsDataURL();
   }
 return input.value || "No file selected";
}

</script>   

Solution

  • This seems to work:

    <html><body>
    
    <h3>Choose an image:</h3>   
        <form><input type='file'  onchange="readURL(this);"  /></form>
    
    
    <h3>preview</h3>    
        <img id="blah" src="#" alt="your image"    /> 
    
    <script type='text/javascript'>
    
    var reader = new FileReader(); 
    reader.onload = function(e) {
      document.images[0].src  = e.target.result; 
    };
    
    function readURL(input){ 
       if(input.files && input.files[0]){
          reader.readAsDataURL(input.files[0]);
       }
       else {
         document.images[0].src = input.value || "No file selected";
       }
    }
    
    </script>
    
    </body></html>