簡體   English   中英

錯誤:無效或損壞的PDF文件Firefox

[英]Error: Invalid or corrupted PDF file Firefox

我正在嘗試上傳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);

看來您對解決方案進行了過度設計

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/

您接受要選擇的多個文件,並且始終使用新的源替換同一iframe。 您無需為每個文件創建新的iframe。 另外,您不必將文件讀取為base64字符串,它毫無意義,而且對性能和內存不利。 您可以改用同步同步的URL.createObjectURL ,這樣就可以消除閉包了

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM