[英]Can't load PDF files larger than 2MB with JS
我的問題與以下帖子幾乎相同某些 PDF 文件無法打開,但在我的情況下更簡單。 我無法加載大於 2MB 的 PDF 文件,較小的文件工作正常。
當我使用readAsDataURL方法時, reader.result似乎被切片。 我將下面的示例(我的案例)生成的 base64 和運行良好的在線工具進行了比較,而我的 bse64 缺少最后一部分(一個很大的部分)。
如果有人對這種行為有所了解並且可以給我一個提示,我將不勝感激。
我的代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="height: 100%;">
<button onclick="getFile(event)">Get File</button>
<input id="pdfInputFile" type="file" accept="application/pdf" style="display:none" onchange="loadPDF(this);" />
<object id="pdfViewer" type="application/pdf" style="height:100%; width:100%;border:solid 1px" >
</object>
</body>
<script>
function getFile(e) {
e.preventDefault();
document.getElementById("pdfInputFile").click();
}
function loadPDF(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("pdfViewer").setAttribute('data', reader.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
</html>
dataurls 有一定的限制,在某些瀏覽器上是 2MB。 另一種方法是使用此處描述的 BLOB-url: 數據協議 URL 大小限制。
我找到了以下文件系統 PDF 文件的解決方案(是我的情況)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="height: 100%;">
<button onclick="getFile(event)">Get File</button>
<input id="pdfInputFile" type="file" accept="application/pdf" style="display:none" onchange="loadPDF(this);" />
<object id="pdfViewer" type="application/pdf" style="height:100%; width:100%;border:solid 1px" >
</object>
</body>
<script>
function getFile(e) {
e.preventDefault();
document.getElementById("pdfInputFile").click();
}
function loadPDF(input) {
if (input.files && input.files[0]) {
showFile(input.files[0])
}
}
function showFile(blob){
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([blob], {type: "application/pdf"});
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
document.getElementById("pdfViewer").setAttribute('data', data);
setTimeout(function(){
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
</script>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.