'File (PDF, JPG, PNG) download instead of opening in new tab

I would like to download document instead opening it in new tab. Files with the extension .docx download normally, but .pdf or .jpg only open in a new tab. I would like PDF and JPG files to be automatically downloaded after clicking like .docx.

HTML (cannot be changed):

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

URL is e.q: https://web-application.com/somefile.pdf

I have tired with FileSaver (NPM intall file-saver) but still not getting downloaded only new tab open.

Ts component:

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);
        }

I've tired also: `

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

or

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

` but with the same effect. Downloading docx files works in any case. I will be grateful for help in solving the problem.



Solution 1:[1]

If you could construct document URLs in render phase, you could use simple HTML link with download attribute, like:

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

See MDN A element download attribute docs.

Solution 2:[2]

To trigger download from button click handler, it should be possible to mimic plain link element with download attribute click. href attribute of that link must either be relative in same origin as document or blob: or data: uri.

POC working in top level page (tested in current Chrome and Firefox), not working here in SO sandbox 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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 myf
Solution 2 myf