Assume that I have an image stored as a variable, from a form, in the form of var someImage = document.getElementById("input1").files[0]. How would I insert this image saved to a variable into an HTML document, without using filepaths?
            Asked
            
        
        
            Active
            
        
            Viewed 334 times
        
    -2
            
            
         
    
    
        DevilApple227
        
- 109
- 7
- 
                    [Preview an image before it is uploaded](https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded) ? – Alex K. Jun 22 '18 at 13:33
- 
                    https://developer.mozilla.org/en-US/docs/Web/API/FileReader – CBroe Jun 22 '18 at 13:34
- 
                    @AlexK. pointed out the correct one. – Alex Jun 22 '18 at 13:34
1 Answers
1
            Yes, see FileReader.readAsDataURL(): read file as data URI.
document.getElementById("input1").onchange = function(e) {
  var someImage = e.target.files[0]
  var reader = new FileReader();
  var img = document.getElementById('preview');
  reader.onload=function(){
    img.src = reader.result
  }
  reader.readAsDataURL(someImage)
}<input type="file" id="input1" accept="image/*" />
<img id="preview" src="" /> 
    
    
        joaner
        
- 706
- 1
- 5
- 17
- 
                    Perhaps this is a local problem, but when I save your code as an HTML file and then open it from my computer the image does not load. I'm using Firefox (up to date) on an Ubuntu. – DevilApple227 Jun 22 '18 at 13:55
- 
                    @DevilApple227 code is no porblem on firefox. Can you see any message from browser Console? It's easy to debug. – joaner Jun 22 '18 at 14:01
- 
                    
- 
                    @DevilApple227 emmm... you should change your element id or something, my code only work for simple example. – joaner Jun 22 '18 at 14:56
- 
                    In what sense? Perhaps I'm wrong, but I thought element ids were arbitrary strings, in the sense that it doesn't matter what you set them to? – DevilApple227 Jun 22 '18 at 15:03
-