簡體   English   中英

文件(pdf、jpg、png)下載而不是在新標簽中打開

[英]File (pdf, jpg, png) download instead of opening in new tab

我想下載文檔而不是在新標簽中打開它。 擴展名為.docx的文件下載正常,但.pdf或.jpg只能在新標簽頁中打開。 我希望點擊like.docx后自動下載pdf和jpg文件。

Html(無法更改):

<div *ngFor="let action of documentActions">
   <button (click)="action.makeAction(element)">
       <mat-icon>{{action.name}}</mat-icon>
    </button>
</div>

url 是 eq: https://web-application.com/somefile.pdf

我已經厭倦了 FileSaver(npm intall 文件保護程序),但仍然沒有下載,只有打開新標簽。

ts 組件:

declare var require: any
const FileSaver = require('file-saver');
(...)
        name: 'download',
        makeAction: (elem: DocumentListItem) =>
        {
          const url = elem.documentUrl;
          const filename = elem.name;
          FileSaver.saveAs(url,filename);
        }

我也累了:

 makeAction: (elem: DocumentListItem) =>
        {
          window.open( elem.documentUrl);
        }

or

   makeAction: (elem: DocumentListItem) =>
        {
          window.location.href =  elem.documentUrl;
        }

但效果相同。 在任何情況下都可以下載 docx 文件。 我將不勝感激幫助解決問題。

問候 !

如果您可以在渲染階段構建文檔 URL,則可以使用帶有download屬性的簡單 HTML 鏈接,例如:

<a href="[URL]" download="[optional suggested file name]">...</a>

請參閱MDN A 元素下載屬性文檔。

要從按鈕單擊處理程序觸發下載,應該可以使用下載屬性單擊模擬普通鏈接元素。 該鏈接的href屬性必須與 document 或blob:data: uri 同源。

POC 在頂級頁面中工作(在當前的 Chrome 和 Firefox 中測試),在 SO 沙箱 iframe 中不工作:

 function dl(url, filename){ var a = document.createElement('a'); a.setAttribute('href',url); a.setAttribute('download', filename||''); document.body.appendChild(a); a.onclick = function(){setTimeout(function(){document.body.removeChild(a)},100)} a.click(); }
 <p>(Not working in SO sandbox iframe.) <p><button onclick=" dl('data:text/plain,test', 'button-download-test.txt') ">download text datauri</button> <p><button onclick=" dl(document.location.href, 'button-download-test.html') ">download this HTML file</button> <p><button onclick=" dl('./probe.png', 'button-download-test.png') ">download png file of same origin</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM