图片上传预览

  1. 适合H5页面,兼容ie10+,图片base64显示,主要功能点是FileReader和readAsDataURL
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>files-h5</title>
</head>
<body>
  <input type="file" id="file" onchange="showPreview(this, 'portrait')" />
  <img src="" id="portrait" style="width: 200px; height: 200px; display: block;" />
  <script>
  function showPreview(source, imgId) {
    var file = source.files[0];
    if(window.FileReader) {
      var fr = new FileReader();
      fr.onloadend = function(e) {
        document.getElementById(imgId).src = e.target.result;
      }
      fr.readAsDataURL(file);
    }
  }
  </script>
</body>
</html>
  1. 更适合PC端,兼容ie7+,主要功能点是window.URL.createObjectURL
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>files-pc</title>
</head>
<body>
  <input type="file" id="file" onchange="showPreview(this.id,'portrait')" />
  <img src="" id="portrait" style="width: 200px; height: 200px; display: block;" />
  <script type="text/javascript">
  /* 图片预览 */
  function showPreview(fileId, imgId) {
    var file = document.getElementById(fileId);
    var ua = navigator.userAgent.toLowerCase();
    var url = '';
    if(/msie/.test(ua)) {
      url = file.value;
    } else {
      url = window.URL.createObjectURL(file.files[0]);
    }
    document.getElementById(imgId).src = url;
  }
  </script>
</body>
</html>

发表评论

电子邮件地址不会被公开。 必填项已用*标注