gpt4 book ai didi

html - 在 HTML 中嵌入通过输入文件元素打开的 PDF

转载 作者:行者123 更新时间:2023-12-05 03:52:03 25 4
gpt4 key购买 nike

我有一个简单的网络应用程序,我需要有人从文件服务器中选择一个 .pdf,然后在网页上显示该 .pdf。

我可以让用户通过类似 <input type="file" id="myFile"> 的方式选择 .pdf

我还可以将 .pdf 嵌入 iframe 以使用 <iframe src="//path/to/file.pdf" width="100%" height="500px"></iframe> 很好地显示在 Web 应用程序上

但是如何显示用户从输入中选择的 .pdf 文件?有没有办法可以将输入值传递到 iframe 的 src 中?我可以在新选项卡或新 html 文件中打开 .pdf,这样我就不必刷新整个页面吗?

最佳答案

对于任何需要帮助的人,我找到了适合我的解决方案。

我为要上传的文件创建了一个输入。此输入调用下面定义的 JS 函数。

<input type="file" id="file-open" onchange="previewFile()" hidden="hidden" accept=".pdf"><br>

然后创建了一个我想要的大小的 iframe

<iframe src="" id="iframe-pdf" width="1200px" height="800px"></iframe>

最后我使用 JavaScript 将文件转换为 base64 并使用 FileReader 在 iframe 中打开文件

function previewFile() {
const preview = document.querySelector('iframe');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
var filename = file.name;

reader.addEventListener("load", function () {
// convert file to base64 string
preview.src = reader.result;
}, false);

if (file) {
reader.readAsDataURL(file);
}

}
</script>

关于html - 在 HTML 中嵌入通过输入文件元素打开的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62430198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com