简体   繁体   中英

Angular 7 initiate browser file download from server with Authorization

I need to implement following functionality using Angular 7 and I have some issues with doing that so probably you can help me here.

We have a service which returns some static files(pdfs) and there is authorization required to call that api. So I invoke API using following method:

  download(uri) { this.http.get(uri, { headers: { 'Authorization': 'Bearer ' + token, 'Accept':'application/pdf' } }).subscribe(()=>{}); 

but what this method actually does - it firstly loads content in memory and then displays it in list of loaded by browser files. What I would want to have - instead firstly loading file in browser memory I would want that browser will be responsible for loading that file and displaying progress of download.

Please let me know if you need any additional details.

PS service responds with header Content-Disposition: attachment

You need actually to use blob since you are using ajax call. first install https://github.com/eligrey/FileSaver.js#readme then

import { saveAs } from 'file-saver';

download(uri) {
this.http.get(uri, {
  headers: {
    'Authorization': 'Bearer ' + token,
     responseType: 'blob' 
  }
}).subscribe((res)=>{
var blob = new Blob(res, {type: "application/pdf"});
saveAs(blob, "file.pdf");
});
  • Your back-end should return array bytes

UPDATE If you want to receive events of download progress you can add observe: 'events' look at download progress

Other Option

  • You can can send a first request ajax to server and in server side generate random URL can be used one time to download file

  • Then use this example and pass the received link in href and trigger click event. like this example

     function download(filename, link) { var element = document.createElement('a'); element.setAttribute('href', link); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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