以下代码可以正常下载远程图像,但在更改为下载远程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>
您可以在a
标签中添加download
属性并删除脚本以下载pdf。
<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" download >Remote PDF</a>
或者如果你想用js下载,考虑在获取
时添加mode:'no-cors'