readAsDataURL

w

http://stackoverflow.com/questions/14069421/show-an-image-preview-before-upload

 1 <input type="file" id="files" />
 2 <img id="image" />
 3 
 4 
 5 <script type="text/javascript">
 6     document.getElementById("files").onchange = function () {
 7         var reader = new FileReader();
 8 
 9         reader.onload = function (e) {
10             // get loaded data and render thumbnail.
11             document.getElementById("image").src = e.target.result;
12         };
13 
14         // read the image file as a data URL.
15         reader.readAsDataURL(this.files[0]);
16     };
17 </script>

 

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

 

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
  <input id="browse" type="file" onchange="previewFiles()" multiple>
<div id="preview"></div>

 </body>
</html>

<script type="text/javascript">
<!--
    
function previewFiles() {

  var preview = document.querySelector('#preview');
  var files   = document.querySelector('input[type=file]').files;

  function readAndPreview(file) {

    // Make sure `file.name` matches our extensions criteria
    if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
      var reader = new FileReader();

      reader.addEventListener("load", function () {
        var image = new Image();
        image.height = 100;
        image.title = file.name;
        image.src = this.result;
        preview.appendChild( image );
      }, false);

      reader.readAsDataURL(file);
    }

  }

  if (files) {
    [].forEach.call(files, readAndPreview);
  }

}

//-->
</script>

 

posted @ 2017-02-06 17:53  papering  阅读(488)  评论(0编辑  收藏  举报