以下代碼可以正常下載遠程影像,但在更改它以下載遠程 PDF 檔案時不起作用,這是我正在使用的代碼:
<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" data-remote>Remote PDF</a>
<script defer type="text/javascript">
const a = document.querySelector('a[data-remote]')
a.addEventListener('click', async (e) => {
e.preventDefault()
const file = await fetch(e.target.href);
const blob = await file.blob();
const blobUrl = URL.createObjectURL(blob);
const downloadLink = document.createElement("a");
downloadLink.href = blobUrl;
downloadLink.download = 'file.pdf';
downloadLink.click();
})
</script>
uj5u.com熱心網友回復:
您可以添加download屬性來a標記并洗掉腳本以下載 pdf。
<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" download >Remote PDF</a>
或者如果你想用js下載的話,考慮mode:'no-cors'在fetch的時候加上
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329736.html
標籤:javascript html pdf 下载
