When want to download a file from server, usually just provide a <a href... will do. But what if the file only allow authorised user to access? Means you have to download first, in this case will have to use http

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { Http, ResponseContentType } from '@angular/http';
...

constructor(
private http: Http,
) { }

downloadFile() {
return this.http
.get('https://jslim.net/path/to/file/download', {
responseType: ResponseContentType.Blob,
search: // query string if have
})
.map(res => {
return {
filename: 'filename.pdf',
data: res.blob()
};
})
.subscribe(res => {
console.log('start download:',res);
var url = window.URL.createObjectURL(res.data);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}

Make sure change the responseType to ResponseContentType.Blob.

Then, in the html file

1
<button class="btn btn-primary" (click)="downloadFile()"><i class="fa fa-file-pdf-o"></i> Download</button>

Now, users are able to download the file when click on the button.

References: