Angular 8|9 Typescript | How to Download PDF/ EXCEL or other files instead of opening in new tab

In this tutorial, we will learn how to download any file type which can be a Doc, Excel, PDF or even images to file system instead of opening them in a new browser tab.

A simple task like downloading a file on the click of a link also sometimes proves so much challenging.

HTML 5 provides a very powerful attribute download which can be added to any <a> element tag to download almost any type of document or file instead of opening them to view.

Default Browser Behaviour

There are some situations where we simply want to use it to download a document. Due to the default behavior of a modern browser which opens the document like PDF in a new tab.

 Problem

We can’t enable you to download the file instead of opening them in a new browser tab which is also restricted sometimes for security reasons.

Solution

Here is a one-stop solution to this scenario.

Simply add the download attribute to the <a> element as shown below:

<a download href="assets/Docs/sample.pdf">Download</a></pre>
<a href="https://www.freakyjolly.com/wp-content/uploads/2020/04/angular-download-link-1.gif"><img class="aligncenter size-full wp-image-3637" src="https://www.freakyjolly.com/wp-content/uploads/2020/04/angular-download-link-1.gif" alt="" width="209" height="50" /></a>

 

<strong>Adding a custom name to the downloaded document</strong>

To add a custom name for the downloaded file, we can provide string value in the download attribute as shown below:
<pre class="wp-block-prismatic-blocks"><code class="language-javascript"><a download="my-custom-file.pdf" href="assets/Docs/sample.pdf">Download</a></pre>
<a href="https://www.freakyjolly.com/wp-content/uploads/2020/04/angular-download-link-2.gif"><img class="aligncenter size-full wp-image-3638" src="https://www.freakyjolly.com/wp-content/uploads/2020/04/angular-download-link-2.gif" alt="" width="209" height="47" /></a>
<h6>Usage in Angular</h6>
To use in Angular, we can convert the <code>href and download attributed to directives to take in dynamic values as shown below:
<a [download]="myFileName" [href]="fileUrl">Download</a>
export class DownloadComponent implements OnInit {

  myFileName = 'my-custom-file.pdf';
  fileUrl = 'assets/Docs/sample.pdf'

...
...

Note: Due to security reasons the download attribute follows same-origin policy so we need to provide same domain of file to be downloaded otherwise the download attribute will be ignored.

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *