简体   繁体   English

下载带有 AJAX 和 HTML 按钮的 PDF 文件(无 jquery)

[英]Download PDF file with AJAX and HTML button (no jquery)

I want to download a PDF file when I press an HTML button.当我按下 HTML 按钮时,我想下载 PDF 文件。 I want the click event to be in a JS file.我希望单击事件位于 JS 文件中。

I need something that do the same thig as the code below but in a JS file:我需要一些与下面的代码相同但在 JS 文件中的东西:

    <a href="url" download>
        <button>Download</button>
    </a>

I tried to follow this but it doesn't create my button:我试图遵循这一点,但它没有创建我的按钮:

var req = new XMLHttpRequest();
req.open("GET", "url", true);
req.responseType = "blob";

req.onreadystatechange = function () {
  if (req.readyState === 4 && req.status === 200) {

    // test for IE

    if (typeof window.navigator.msSaveBlob === 'function') {
      window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");
    } else {
      var blob = req.response;
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = "PdfName-" + new Date().getTime() + ".pdf";

      // append the link to the document body

      document.body.appendChild(link);

      link.click();
    }
  }
};
req.send();

Just made it work, here is my working code刚刚成功,这是我的工作代码

const blob = new Blob([response], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "filename.pdf";
link.click();

If you already have the URL, and you just want the file to be downloaded, use an invisible link, and click it for the user:如果您已经拥有 URL,并且只想下载文件,请使用不可见链接,然后为用户单击它:

function triggerDownload(url, filename) {
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.style.display = `none`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

Note the adding to the document, which is required for the link to count as a real link.请注意添加到文档中,这是链接算作真实链接所必需的。

I would agree with mike, you don't need any ajax to download it if you want to add the timestamp for when you downloaded it, just change the download attribute dynamical我同意迈克的观点,如果你想在下载时添加时间戳,你不需要任何 ajax 来下载它,只需动态更改下载属性

<a href="url" onclick="this.download = `PdfName-${+new Date}.pdf`">Download</a>

or better yet add it in the backend using content-disposition attachment header或者更好的是使用内容处置附件 header 将其添加到后端

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

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