Understanding <input type=“file”>

百般思念 提交于 2020-01-03 10:18:30

问题


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.


回答1:


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.




回答2:


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 :)



来源:https://stackoverflow.com/questions/12107346/understanding-input-type-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!