纯前端 文件预览方法汇总

发布时间:2023年12月31日

????????以下是通过javaScript的方法实现文件预览的方法汇总:

1.使用HTML5的File API和Canvas来预览图片文件:

<!DOCTYPE html>
<html>
<head>
  <title>Image Preview</title>
</head>
<body>
  <input type="file" id="fileInput">
  <img id="previewImage">

  <script>
    document.getElementById('fileInput').addEventListener('change', function() {
      var file = this.files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        document.getElementById('previewImage').src = e.target.result;
      };
      reader.readAsDataURL(file);
    });
  </script>
</body>
</html>

2.使用HTML5的File API和Video标签来预览视频文件:

<!DOCTYPE html>
<html>
<head>
  <title>Video Preview</title>
</head>
<body>
  <input type="file" id="fileInput">
  <video id="previewVideo" controls></video>

  <script>
    document.getElementById('fileInput').addEventListener('change', function() {
      var file = this.files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        document.getElementById('previewVideo').src = e.target.result;
      };
      reader.readAsDataURL(file);
    });
  </script>
</body>
</html>

3.使用第三方库如PDF.js来预览PDF文件:

<!DOCTYPE html>
<html>
<head>
  <title>PDF Preview</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.8.335/pdf.min.js"></script>
</head>
<body>
  <input type="file" id="fileInput">
  <iframe id="previewPDF" width="100%" height="500px"></iframe>

  <script>
    document.getElementById('fileInput').addEventListener('change', function() {
      var file = this.files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        var fileData = new Uint8Array(e.target.result);
        pdfjsLib.getDocument({data: fileData}).promise.then(function(pdf) {
          pdf.getPage(1).then(function(page) {
            var scale = 1.5;
            var viewport = page.getViewport({ scale: scale });
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            var renderContext = {
              canvasContext: context,
              viewport: viewport
            };
            page.render(renderContext).promise.then(function() {
              document.getElementById('previewPDF').src = canvas.toDataURL();
            });
          });
        });
      };
      reader.readAsArrayBuffer(file);
    });
  </script>
</body>
</html>
文章来源:https://blog.csdn.net/qq_44327851/article/details/135224127
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。