Object URLs can be used for other things than just images! They can be used to display embedded PDF files or any other resources that can be displayed by the browser.
In Firefox, to have the PDF appear embedded in the iframe (rather than proposed as a downloaded file), the preference pdfjs.disabled
must be set to false
.
<iframe id="viewer">
And here is the change of the src
attribute:
const obj_url = URL.createObjectURL(blob);
const iframe = document.getElementById(‘viewer‘);
iframe.setAttribute(‘src‘, obj_url);
URL.revokeObjectURL(obj_url);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Using object URLs to display PDF</title>
</head>
<body>
<input type="file" accept=".pdf" />
<br />
<iframe width="100%" height="500"></iframe>
<script type="text/javascript">
window.onload = (event) => {
console.log(event)
const input = document.querySelector(‘input[type=file]‘)
const iframe = document.querySelector(‘iframe‘)
console.log(input, iframe)
input.onchange = (event) => {
console.log(event)
const files = event.target.files
if (files.length > 0) {
const objectURL = URL.createObjectURL(files[0])
iframe.setAttribute(‘src‘, objectURL)
URL.revokeObjectURL(objectURL)
}
}
}
</script>
</body>
</html>
Example: Using object URLs to display PDF
Web API - File - Using object URLs to display PDF
原文:https://www.cnblogs.com/Satu/p/14646109.html