Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:\fakepath\image.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.

like image 772
Flicks Gorger Avatar asked Jul 29 '15 20:07

Flicks Gorger


People also ask

Can JavaScript display images?

Create “show()” function in JavaScript which can get the image and add the image source link to the src attribute.

How do you insert an image into JavaScript?

Access an Input Image Object You can access an <input> element with type="image" by using getElementById(): var x = document. getElementById("myImage"); Tip: You can also access <input type="image"> by searching through the elements collection of a form.


1 Answers

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">
like image 89
Carl Edwards Avatar answered Oct 04 '22 17:10

Carl Edwards