错误:Firefox文件无效或损坏

时间:2017-12-02 07:08:35

标签: javascript pdf firefox file-upload

我正在尝试上传PDF文件,一旦完成上传,我试图在IFrame中显示PDF文件,其中包含我在范围内的流内容。如果我上传图像文件但在Firefox中上传PDF上传时出现以下错误,则相同的代码有效。

错误

Invalid or corrupted PDF file.
PDF.js v1.9.583 (build: d7b37ae7)
Message: Invalid PDF structure
viewer.js:1359:7
Error: Invalid or corrupted PDF file.

HTML

<input type="file" id="files" name="files[]" multiple />

<iframe id="uploadedFileIframe" title="PDF in an i-Frame" src=""  scrolling="auto" height="400" width="400" />

CSS

  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }

的JavaScript

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('pdf.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.

          var enc = btoa(unescape(encodeURIComponent( e.target.result)))
          document.getElementById('uploadedFileIframe').setAttribute('src','data:application/pdf;base64,'+ enc);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);

2 个答案:

答案 0 :(得分:0)

看起来你已经过度设计了解决方案

document.getElementById('uploadedFileIframe').src = reader.result;

如果放置它而不是

,则应该有效
var enc = btoa(unescape(encodeURIComponent( e.target.result)))   
document.getElementById('uploadedFileIframe').setAttribute('src','data:application/pdf;base64,'+ enc);

https://jsfiddle.net/kc8sdas5/

答案 1 :(得分:0)

您正在接受多个要选择的文件,并且您始终使用新来源替换相同的iframe。您不为每个文件创建新的iframe。此外,您不必将文件读取为base64字符串,这对于性能和内存来说也毫无意义。你可以改为使用URL.createObjectURL代替syncron,这样你就可以摆脱你的闭包

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    var previews = document.querySelector('#previews');
    var iframe;
    var URL = window.URL || webkitURL;
    
    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
      // Only process pdf files.
      if (!f.type.match('pdf.*')) {
        continue;
      }

      iframe = document.createElement('iframe')
      iframe.title = "PDF in an i-Frame";
      iframe.scrolling = "auto";
      iframe.width = iframe.hight = 400;
      iframe.src = URL.createObjectURL(f);

      previews.appendChild(iframe);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" name="files[]" multiple />

<div id="previews"></div>