Angular 2 downloading a file: corrupt result

后端 未结 2 949
走了就别回头了
走了就别回头了 2020-12-30 12:52

I am attempting to download a file using Angular 2/TypeScript and Web API. The problem I am having is that when downloading the text file, the file is file but when attempti

2条回答
  •  借酒劲吻你
    2020-12-30 13:04

    As of Angular RC5 following code should work for you:

    downloadFile(fileId: string): Observable {
    this.applicationsUrl = `${APIConfig.BaseUrl}/documents/download/${fileId}/`;
    
    let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' });
    let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
    
    return this.http.post(this.applicationsUrl, '', options)
        .map(this.extractContent)
        .catch(this.handleError);
    }
    
    private extractContent(res: Response) {
        let blob: Blob = res.blob();
        window['saveAs'](blob, 'test.pdf');
    }
    

    I had a similar Problem and setting the Accept-Header to application/pdf, responseType to Blob and accessing the blob through the corresponding Method on the Response resolved this for me :) (I'm using FileSaver, too)

提交回复
热议问题