我正在尝试使用Angular 2 / TypeScript和Web API下载文件。我遇到的问题是,在下载文本文件时,该文件是文件,但在尝试下载PDF文件时,例如,它已损坏。下载文件的内容是乱码。
我正在使用的TypeScript如下:
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');
}
窗口['saveAs']只是一种访问JavaScript FileSaver.js函数的解决方法。
另外我设置了res:响应res:any所以我可以在JavaScript下访问private _body属性而不会在TypeScript中出现编译失败。
非常感谢任何帮助。
答案 0 :(得分:10)
从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');
}
我有一个类似的问题并将Accept-Header设置为application/pdf
,responseType设置为Blob
并通过响应上的相应方法访问blob解决了这个问题:)
(我也在使用FileSaver)
答案 1 :(得分:0)
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 :-
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>>
converters) {
//Here we add our custom-configured HttpMessageConverter
/* Message converter for supporting Hibernate lazy objects */
converters.add(jacksonMessageConverter());
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
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.