Angular: How to download a file from HttpClient?

后端 未结 6 1628
挽巷
挽巷 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:09

    Try something like this:

    type: application/ms-excel

    /**
     *  used to get file from server
     */
    
    this.http.get(`${environment.apiUrl}`,{
              responseType: 'arraybuffer',headers:headers} 
             ).subscribe(response => this.downLoadFile(response, "application/ms-excel"));
    
    
        /**
         * Method is use to download file.
         * @param data - Array Buffer data
         * @param type - type of the document.
         */
        downLoadFile(data: any, type: string) {
            let blob = new Blob([data], { type: type});
            let url = window.URL.createObjectURL(blob);
            let pwa = window.open(url);
            if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
                alert( 'Please disable your Pop-up blocker and try again.');
            }
        }
    

提交回复
热议问题