简体   繁体   English

Javascript 代码可以很好地下载图像,但不能下载 PDF 文件

[英]Javascript code works fine to download images but not to download a PDF file

The following code works properly to download remote images, but did not work when altering it to download remote PDF file, here is the code I am using:以下代码可以正常下载远程图像,但在更改它以下载远程 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>

You could add download property to a tag and remove the script to download the pdf.你可以添加download属性, a标签和删除脚本下载PDF格式。

<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" download >Remote PDF</a>

Or if you want to use js to download it, consider to add mode:'no-cors' when you fetch或者如果你想用js下载,可以考虑在fetch mode:'no-cors'时候加上mode:'no-cors'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM