9

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>
Nope
  • 21,584
  • 7
  • 42
  • 72
user3335903
  • 1,175
  • 4
  • 12
  • 12

2 Answers2

16
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

Nephelococcygia
  • 387
  • 1
  • 9
-2

be carrefull : reader.onloadend = function { must be reader.onloadend = function() {

but why use a fileReader ? For exemple my function to add pictures in my webSite =>

function createImageBase(src, alt) {
    var image = document.createElement('img');
    image.src = src;
    image.alt = alt;
    return image;
}


function addPicture(targetID, imageSRC){
   var location = document.getElementById(targetID);
   var image = createImageBase(imageSRC, imageSRC);
   location.appendChild(image);
}

Then just call it like that : Display

daarksim
  • 225
  • 1
  • 9
  • Do you have any working sample for it? I tried to use it but it didn't work. – user3335903 Mar 07 '14 at 08:50
  • I use it for my application who is here : http://test.projet1.worldheberg.com/local/fr-appli-test.html (all the image are not in the server that's why you can show few missing images) Can you publish your link ? – daarksim Mar 07 '14 at 08:54
  • Where do u get the imgSRC if the file is on client's machine. This basically adds an img element to the DOM (pretty straight forward). The question is how to display an image from a file input, – Amiratak88 Jun 08 '19 at 23:38