[英]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.
<input type="file" id="files" name="files[]" multiple />
<iframe id="uploadedFileIframe" title="PDF in an i-Frame" src="" scrolling="auto" height="400" width="400" />
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
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);
您接受要选择的多个文件,并且始终使用新的源替换同一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.