Skip to content
Advertisement

Javascript image upload and display

My basic task is select image and display it,without saving it in database.

For this

1.I have made a select tag in html,through which I can upload the image.

2.I have made a blank image tag in which at there is no image source,alternate is upload image.

3.select tag has onchange javascript event handler which calls javascript function changeimage.

<script>
       function changeimage()
       {
            document.form_name.imagetag.src=document.form_name.filetag.value;
       }
</script>

In above Code

form_name : Is the name of my form

<form name = "form_name">

imagetag : Is the name of my Img tag

<Img src=" " name = "imagetag">

filetag : Is the name of my

<input type="file" name = "filetag" onchange="changeimage()">

I have save file using php extension.And when I try to print the value of filetag it shows “C:fakepathimage.png”,display this address for all image. I have save my php file in www location.

I am using window 7,wamp server and chrome latest version.

Advertisement

Answer

You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.

Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.

var fileTag = document.getElementById("filetag"),
    preview = document.getElementById("preview");
    
fileTag.addEventListener("change", function() {
  changeImage(this);
});

function changeImage(input) {
  var reader;

  if (input.files && input.files[0]) {
    reader = new FileReader();

    reader.onload = function(e) {
      preview.setAttribute('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}
<input type="file" id="filetag">
<img src="" id="preview">
Advertisement