简体   繁体   English

如何在单击时自动下载 PDF 而不是使用 js 在新选项卡中打开它?

[英]How to download PDF automatically on click instead of opening it in new tab using js?

I have an input URL with which I want to download pdf file directly without viewing it in a new tab or on the same tab, I have tried following things till now but nothing is helping.我有一个输入 URL,我想直接下载 pdf 文件而不在新选项卡或同一选项卡上查看它,到目前为止我已经尝试过以下操作但没有任何帮助。 Frist tried with this第一次尝试这个

http.success(function (data) {
  var link = document.createElement('a');
  link.href = data.results[0].value.url;
  link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
  link.click();
  document.body.appendChild(link);
  setTimeout(function () {
  document.body.removeChild(link);
     }, 100);
}.bind(this));

This script is not downloading the file.此脚本不下载文件。 It opens the file in the same tab.它在同一选项卡中打开文件。 Have tried all the answers in these previously answered questions.已经尝试了这些先前回答的问题中的所有答案。 But nothing worked for me.但对我没有任何帮助。 How can I download a pdf from a url using javascript? 如何使用 javascript 从 url 下载 pdf? How to download PDF automatically using js? 如何使用js自动下载PDF? Download pdf without opening in browser 不用浏览器打开下载pdf

Then I tried with this Blob .然后我尝试使用这个Blob Added the blob to my script and then tried again.将 blob 添加到我的脚本中,然后重试。

http.success(function (data) {
  var blob=new Blob([data.results[0].value.url],{ type: "application/pdf" });
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
  link.click();
  document.body.appendChild(link);
  setTimeout(function () {
  document.body.removeChild(link);
     }, 100);
}.bind(this));

But this time it downloads the file.但是这次它下载了文件。 But can't able to open it.但是无法打开它。 The downloaded file is corrupted.下载的文件已损坏。 Have tried the answers in these questions.已经尝试过这些问题的答案。 But nothing worked for me.但对我没有任何作用。 PDF is corrupted after reconstructing it using URL.createObjectURL Problem downloading a PDF blob in JavaScript Blob from buffer returns corrupted pdf PDF 在使用 URL.createObjectURL 重建后损坏 在 JavaScript 中下载 PDF blob 从缓冲区返回损坏的 pdf Blob 时出现问题

please let me know if there are any other ways to download the pdf file directly.如果有任何其他方法可以直接下载 pdf 文件,请告诉我。 Thanks in advance.提前致谢。

What is stored in data.results[0].value.url? data.results[0].value.url 中存储了什么?

Is it just a link to the PDF?它只是指向PDF的链接吗? If that's the case you will need to fetch the pdf document first.如果是这种情况,您需要先获取 pdf 文档。

Try this尝试这个

http.success(function (data) {
  fetch(data.results[0].value.url)
    .then((response) => response.arrayBuffer())
    .then((pdfFile) => {
      const blob = new Blob([pdfFile], { type: "application/pdf" });

      const anchor = document.createElement("a");

      anchor.href = window.URL.createObjectURL(blob);
      anchor.download = "SOME FILENAME.PDF";
      // some browser needs the anchor to be in the doc
      document.body.append(anchor);
      anchor.click();
      anchor.remove();
      // in case the Blob uses a lot of memory
      window.addEventListener(
        "focus",
        () => {
          URL.revokeObjectURL(anchor.href);
        },
        {
          once: true,
        }
      )
    });
})

First, I would recommend trying the simplest example.首先,我建议尝试最简单的例子。

const pdfLink = data.results[0].value.url

const download = (url) => {
    const link = document.createElement('a');

    link.setAttribute('download', 'fileName.pdf');
    link.setAttribute('href', url);
    link.click();
}

downloadBlob = (blob) => download(URL.createObjectURL(blob))

fetch(pdfLink)
  .then(response => response.blob())
  .then(downloadBlob)

I share you a piece of code using MUI + JS我用 MUI + JS 给你分享一段代码

<IconButton variant="contained"
                      sx={{
                        fontSize: '1rem',
                        fontWeight: 'normal',
                        color:'silver',
                      }}
                      component='label'
                      size={'small'}
                      onClick={() => {
                        const url = 'https:.....'
                        fetch(url)
                          .then((res) => { return res.blob(); })
                          .then((data) => {
                            const a = document.createElement("a")
                            a.href = window.URL.createObjectURL(data)
                            a.download = formValues[id]
                            a.click()
                          });
                      }}>
    <VisibilityIcon />
</IconButton>

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

相关问题 文件(pdf、jpg、png)下载而不是在新标签中打开 - File (pdf, jpg, png) download instead of opening in new tab 从 URL 下载 pdf 而不是在新选项卡中打开 - Download pdf from a URL instead of opening in a new tab 点击下载MP3而不是打开标签 - Download MP3 on click instead of opening tab 如何使用js自动下载PDF? - How to download PDF automatically using js? 如何在模态中显示 pdf 而不是在 React js 中以新的 window 打开它 - how to show the pdf in a modal instead of opening it in a new window in react js 如何通过点击链接下载图像而不是打开它 - How to download a image on link click instead of opening it 在浏览器中打开 pdf 和视频新标签,而不是使用第三方插件下载 - Opening a pdf and videos new tab in a browser instead of dowloading using third party plugins 单击按钮而不是打开新选项卡(HTML 或 JavaScript)时如何触发文件下载 - How to trigger a file download when clicking an button instead opening a new tab (HTML or JavaScript) 如何在不打开新选项卡中的图像的情况下在锚点标签上下载图像文件? - How to download image file on anchor tag click without opening image in new tab? 在新标签页中打开网址,而不是弹出窗口(点击后) - Opening an url in a new tab instead of a popup (after click)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM