Angular 2下载文件:结果损坏 [英] Angular 2 downloading a file: corrupt result

查看:168
本文介绍了Angular 2下载文件:结果损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Angular 2/TypeScript和Web API下载文件.我遇到的问题是,在下载文本文件时,该文件是文件,但是在尝试下载PDF文件时,例如,该文件已损坏.下载文件的内容是乱码.

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 attempting to download an PDF file, for example, it is corrupted. The contents of the downloaded file is garbled nonsense.

我正在使用的TypeScript如下:

The TypeScript I am using is as follows:

downloadFile(fileId: string): Observable<File> {
    this.applicationsUrl = `${APIConfig.BaseUrl}/documents/download/${fileId}/`;

    let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.applicationsUrl, '', options)
        .map(this.extractContent)
        .catch(this.handleError);
}

private extractContent(res: any) {
    let blob: Blob = new Blob([res._body], { type: 'application/pdf'});
    window['saveAs'](blob, 'test.pdf');
}

window ['saveAs']只是访问JavaScript FileSaver.js函数的一种解决方法.

The window['saveAs'] is just a workaround to access the JavaScript FileSaver.js functions.

此外,我将res:Response设置为res:any,因此我可以在JavaScript下访问private _body属性,而不会在TypeScript中编译失败.

Additionally I have set res:Response to res:any so I can access the private _body property under JavaScript without a compile failure in TypeScript.

任何帮助将不胜感激.

推荐答案

从Angular RC5开始,以下代码将为您工作:

As of Angular RC5 following code should work for you:

downloadFile(fileId: string): Observable<File> {
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');
}

我有一个类似的问题,将Accept-Header设置为application/pdf,responseType设置为Blob,并通过Response上的相应方法访问Blob,为我解决了这个问题:) (我也在使用FileSaver)

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)

这篇关于Angular 2下载文件:结果损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆