1

How to upload an image and display it in the same page using html, javascript / jquery, just like we do in facebook and instagram. Can anyone help Please?

  • 1
    Include just enough code to allow others to reproduce the problem. For help with this, read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Shubham Baranwal Mar 13 '19 at 09:44

2 Answers2

4

Try this

window.addEventListener('load', function() {
  document.querySelector('input[type="file"]').addEventListener('change', function() {
    if (this.files && this.files[0]) {
      var img = document.querySelector('img'); // $('img')[0]
      img.src = URL.createObjectURL(this.files[0]); // set src to file url
    }
  });
});
<input type='file' />
<br>
<img id="myImg" src="#" alt="your image" width="100" height="100">
Shubham Baranwal
  • 2,492
  • 3
  • 14
  • 26
1

Try This ....Very Simple

function showMyImage(fileInput) {
      var files = fileInput.files;
        //console.log(files);
        for (var i = 0; i < files.length; i++) {           
            var file = files[i];
            console.log(file.name);
            var imageType = /image.*/;     
            if (!file.type.match(imageType)) {
                continue;
            }           
            var img=document.getElementById("thumbnil");            
            img.file = file;    
            var reader = new FileReader();
            reader.onload = (function(aImg) { 
                return function(e) { 
                    aImg.src = e.target.result; 
                }; 
            })(img);
            reader.readAsDataURL(file);
            thumbnil.style.display = 'block';
            //$("#banner_name").text(file.name);

        }
  }
<input type='file' id="upload" onchange="showMyImage(this)" />
<img id="thumbnil" style="width:100%; max-width: 200px; margin:10px 0; display:none;"  src="" alt="logo"/>
Mohit Arya
  • 49
  • 3