typescript Angular 2 下载文件:损坏的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38793859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 downloading a file: corrupt result
提问by Bren Gunning
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.
我正在尝试使用 Angular 2/TypeScript 和 Web API 下载文件。我遇到的问题是,下载文本文件时,该文件是文件,但当尝试下载 PDF 文件时,例如,它已损坏。下载的文件内容是乱码胡说八道。
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');
}
The window['saveAs'] is just a workaround to access the JavaScript FileSaver.js functions.
window['saveAs'] 只是访问 JavaScript FileSaver.js 函数的一种解决方法。
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.
此外,我已将 res:Response 设置为 res:any,以便我可以访问 JavaScript 下的私有 _body 属性,而不会在 TypeScript 中编译失败。
Any help would be greatly appreciated.
任何帮助将不胜感激。
回答by Chris
As of Angular RC5 following code should work for you:
从 Angular RC5 开始,以下代码应该适合您:
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');
}
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)
我有一个类似的问题,将 Accept-Header 设置为application/pdf
, responseTypeBlob
并通过响应上的相应方法访问 blob 为我解决了这个问题:)(我也在使用 FileSaver)
回答by java dev
We were having a similar issue and had to configure a messageConverter on the spring side. The code snippet below is from Spring config file :-
我们遇到了类似的问题,不得不在 spring 端配置一个 messageConverter。下面的代码片段来自 Spring 配置文件:-
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>>
converters) {
//Here we add our custom-configured HttpMessageConverter
/* Message converter for supporting Hibernate lazy objects */
converters.add(HymansonMessageConverter());
converters.add(byteArrayHttpMessageConverter());
super.configureMessageConverters(converters);
}
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.APPLICATION_OCTET_STREAM);
list.add(MediaType.parseMediaType("application/pdf"));
return list;
}
More details on configuring message converters can be found here:- http://www.baeldung.com/spring-httpmessageconverter-rest
可以在此处找到有关配置消息转换器的更多详细信息:- http://www.baeldung.com/spring-httpmessageconverter-rest
You still need to add the "Accept" header in the request as answered by Chris. This will help map the response to an appropriate message converter configured on the spring side.
您仍然需要在 Chris 回答的请求中添加“接受”标头。这将有助于将响应映射到在 spring 端配置的适当消息转换器。