【问题标题】:Download pdf without opening in browser无需在浏览器中打开即可下载 pdf
【发布时间】:2020-12-22 15:53:47
【问题描述】:

我想直接下载 pdf 文件而不查看,我一直在尝试跟踪,但没有任何帮助。

1- window.open("https://s3-link1.pdf", 'Download');

2- <a href="https://s3-link1.pdf" download>Link</a>

链接 - https://s3-link1.pdf

假设我的域是 https://www.somedomain.com

我在某处读到我们无法下载跨域文件。 content-disposition 标头需要从后端传递。我在这里感到困惑。另一个跨域的csv文件正在轻松下载。

https://s3-link2.csv

我只需要使用 javascript 下载 pdf 文件。请指导我。

【问题讨论】:

  • 不确定上下文。您可以右键单击链接并从上下文菜单中单击“另存为...”。
  • 您想要一个脚本,可以复制粘贴到浏览器控制台并从您当前查看的页面批量下载链接吗?
  • 我认为她的意思是只要它点击 url。文件应该会自动下载

标签: javascript html reactjs pdf render


【解决方案1】:

尝试使用 fetch。

fetch("https://s3-link1.pdf", {
    method: 'GET'
}).then(resp => resp.blob())
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = "name"; // the filename you want
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
    })

【讨论】:

    【解决方案2】:

    选项 1: 使用 jQuery 你可以试试这个:

    $.get("https://s3-link1.pdf", function (result)
    {
        var blob = new Blob([result]);
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "myFileName.pdf";
        link.click();
    });
    

    选项 2: download 属性适用于所有现代浏览器,包括 MS Edge,但不适用于 Internet Explorer。

    在最新版本的 Chrome 中,您无法下载跨域文件(它们必须托管在同一域中)。

    <a href="https://s3-link1.pdf" download>Download PDF</a>
    

    在此博客上了解更多信息:https://actualwizard.com/html-force-download-file

    【讨论】:

    • 选项 2:跨域链接正在使用 window.open() 工作,csv 可以轻松下载,但如果它是 pdf,则不会。为什么这样? supply-guide.s3-ap-southeast-1.amazonaws.com/…
    • 它没有下载,它跟随 URL,对于那个文件类型'csv',浏览器执行保存文件的默认操作,而对于'pdf',默认操作是打开文件在浏览器中。使用“下载”属性时,您可能会遇到 CORS 问题。
    猜你喜欢
    • 1970-01-01
    • 2011-08-15
    • 2017-07-06
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多