Angular: How to download a file from HttpClient?

后端 未结 6 1621
挽巷
挽巷 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

    Blobs are returned with file type from backend. The following function will accept any file type and popup download window:

    downloadFile(route: string, filename: string = null): void{
    
        const baseUrl = 'http://myserver/index.php/api';
        const token = 'my JWT';
        const headers = new HttpHeaders().set('authorization','Bearer '+token);
        this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe(
            (response: any) =>{
                let dataType = response.type;
                let binaryData = [];
                binaryData.push(response);
                let downloadLink = document.createElement('a');
                downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType}));
                if (filename)
                    downloadLink.setAttribute('download', filename);
                document.body.appendChild(downloadLink);
                downloadLink.click();
            }
        )
    }
    

提交回复
热议问题