Understanding <input type="file">

Jamie Fearon picture Jamie Fearon · Aug 24, 2012 · Viewed 14k times · Source

I am trying to get my head around and using the selected image in a website.

Let's say I have a simple website that lets the user select an image from their system using:

<input type="file" id="userImage">

Then in the JavaScript I can do this to get the file:

var userImage = document.getElementById('#userImage').files[0]; 

Questions:

1) Can I now use userImage? Such as drawing it on a canvas, or do I need to uploaded it to the websites server first?

2) If I use the image, does the website have to upload it every-time I use it, or does it stay in memory?

3) How do I know when the image is ready to use? (for the same reasons all images should be preloaded at the start before drawn on canvas)

Thanks so much for your help :)

Follow-up

Thanks for your answers. So it looks like it is possible in html5 but not yet universally supported.

Answer

tbl picture tbl · Aug 24, 2012

In HTML4 this would not be possible, but in HTML5 you should be able to access local files using the W3 File API. However, I'm not sure when (and how) it will be supported by the different browsers. In my local firefox 14.0.1, the following code works and yields the binary data of the selected file:

var reader = new FileReader()
reader.readAsDataURL(document.getElementById('userImage').files[0])
alert(reader.result)

The following page paints a local image onto a canvas:

<html>
  <body>
    <script type="text/javascript">
      function doIt() {
        var reader = new FileReader();
        reader.onload = (function(e) {
            var img = new Image();
            img.src = e.target.result;
            var c = document.getElementById("canvas");
            var ctx = c.getContext("2d");
            ctx.drawImage(img,10,10);
          }
        );
        reader.readAsDataURL(document.getElementById('userImage').files[0]);
      }
    </script>

    <input type="file" id="userImage" />
    <button onclick="doIt()">Render Image</button><br/>
    <canvas id="canvas" style="border: 1px solid black; height: 400px; width: 400px;"/>
  </body>
</html>

Maybe you should consider reading 2.