Angular: How to download a file from HttpClient?

后端 未结 6 1608
挽巷
挽巷 2020-12-04 23:57

I need download an excel from my backend, its returned a file.

When I do the request I get the error:

TypeError: You provided \'undefined\' wh

6条回答
  •  时光取名叫无心
    2020-12-05 00:24

    Using Blob as a source for an img:

    template:

    
    

    component:

     public url : SafeResourceUrl;
    
     constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
       this.getImage('/api/image.jpg').subscribe(x => this.url = x)
     }
    
     public getImage(url: string): Observable {
       return this.http
         .get(url, { responseType: 'blob' })
         .pipe(
           map(x => {
             const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
             return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
           }),
         );
     }
    

    Further reference about trusting save values

提交回复
热议问题