FileReader.readAsDataURL()

readAsDataURL 方法会读取指定的 Blob 或 File 对象。读取操作完成的时候,readyState 会变成已完成DONE,并触发 loadend 事件,同时 result 属性将包含一个data:URL格式的字符串(base64编码)以表示所读取文件的内容。

语法

instanceOfFileReader.readAsDataURL(blob);

参数

blob
即将被读取的 Blob 或 File 对象。

示例

HTML

<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

JavaScript

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    preview.src = reader.result;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}

演示

读取多个文件的例子

HTML

<input id="browse" type="file" onchange="previewFiles()" multiple>
<div id="preview"></div>

JavaScript

function previewFiles() {

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

  function readAndPreview(file) {

    // 确保 `file.name` 符合我们要求的扩展名
    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);
  }

}
注意: Internet Explorer  10 之前的版本并不支持  FileReader() 。关于图片文件预览的兼容性解决方案,可以查看 crossbrowser possible solution for image preview 或者 this more powerful example 。

规范

Specification Status Comment
File API
FileReader
Working Draft Initial definition

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
readAsDataURLChrome Full support 7Edge Full support 12Firefox Full support 3.6IE Full support 10Opera Full support 11Safari Full support 6WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 32
Notes
Full support 32
Notes
Notes Using the camera in Android 8.x raises an exception. See bug 1511083.
Opera Android Full support 11Safari iOS Full support 6.1Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.

参见