Understanding <input type="file">
Asked Answered
A

2

7

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.

Allness answered 24/8, 2012 at 10:10 Comment(0)
D
17

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.

Dunstan answered 24/8, 2012 at 10:29 Comment(2)
Thanks for your answers. So it looks like it is possible in html5 but not yet universally supported.Allness
You can find up to date information about support for the FileReader API at caniuse.com/#feat=filereaderBarthol
C
-3

1) You can not open or modify image because client-side scripts are execute in browser sandbox. If scripts can access to filesystem or user files it will be a security issue

2) No, browser send file himself block-by-block to remote server

3) See item 1 :)

Catarrhine answered 24/8, 2012 at 10:15 Comment(1)
For people who downvote this answer: at these time there was no support for accessing file from the clientCatarrhine

© 2022 - 2024 — McMap. All rights reserved.