Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an image from a file input? [duplicate]

Tags:

javascript

I would like to choose a file and display the image on the browser. I tried inserting the direct image path and it worked.

The problem now is, how can I display the image from the <input type=file> ?

Here is what my code looks like:

function myFunction() {
    var file = document.getElementById('file').files[0];
    var reader = new FileReader();

    reader.onloadend = function {
        var image = document.createElement("img");
        image.src = "reader"
        image.height = 200;
        image.width = 200;

        document.body.appendChild(image);
    }
}
<input type=file name=filename id=file>
<button type=button onclick='myFunction()'>Display</button>
like image 483
user3335903 Avatar asked Mar 07 '14 08:03

user3335903


People also ask

How display image from input type file react?

To display a image selected from file input in React, we can call the URL. createObjectURL with the selected file object to and set the returned value as the value of the src prop of the img element. We define the img state which we use as the value of the src prop of the img element.


1 Answers

function myFunction() {

    var file = document.getElementById('file').files[0];
    var reader  = new FileReader();
    // it's onload event and you forgot (parameters)
    reader.onload = function(e)  {
        var image = document.createElement("img");
        // the result image data
        image.src = e.target.result;
        document.body.appendChild(image);
     }
     // you have to declare the file loading
     reader.readAsDataURL(file);
 }

http://jsfiddle.net/Bwj2D/11/ working example

like image 114
Nephelococcygia Avatar answered Sep 19 '22 13:09

Nephelococcygia