简体   繁体   English

在同一页面中将 PDF 链接下载为文件,而不是在浏览器中打开

[英]Download a PDF link as a file in the same page instead of opening in browser

In my application written in Ionic 5 and Angular 8, I am in need to download multiple PDF links (file) in the same page on click of the link.在我用 Ionic 5 和 Angular 8 编写的应用程序中,我需要在单击链接时在同一页面中下载多个 PDF 链接(文件)。 I tried but the PDF links are opening in browser.我试过了,但 PDF 链接正在浏览器中打开。 Request to help me achieve this functionality.请求帮助我实现此功能。

https://stackblitz.com/edit/ionic-yzzwov?file=pages%2Fhome%2Fhome.html https://stackblitz.com/edit/ionic-yzzwov?file=pages%2Fhome%2Fhome.html

The download attribute appears normal when same-origin, otherwise it will appear the same as without download attribute.同源时有下载属性正常显示,否则显示为无download属性。 list three solutions:列出三个解决方案:

  1. Package the file into a file type that cannot be opened directly by the browser, such as ZIP Package 将文件改成浏览器无法直接打开的文件类型,如ZIP
  2. Through forwarding by the back end, the back end requests a third-party resource and returns it to the front end, which saves the file using tools such as file-Saver通过后端转发,后端请求第三方资源返回给前端,前端使用file-Saver等工具保存文件
  3. If the third-party resource the URL points to has CORS configured, you can request the file through XHR如果URL指向的第三方资源配置了CORS,可以通过XHR请求文件
downloadFileXHR(filePath, fileName) {
   var xhh = new XMLHttpRequest()
   xhh.open('get', filePath)
   xhh.responseType = 'blob'
   xhh.onreadystatechange = function () {
     if (xhh.readyState === 4 && xhh.status === 200) {
       var blob = new Blob([xhh.response])
       var csvUrl = URL.createObjectURL(blob)
       var link = document.createElement('a')
       link.href = csvUrl
       link.download = fileName
       link.click()
     }
   }
   xhh.send()

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

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