MVC控制器方法返回一个pdf文件:
public ActionResult GetLetterHistoryBatchPdf(int letterBatchID)
{
return File(System.IO.File.OpenRead(@"\\ThePath\thepdf.pdf"), "application/pdf");
}
angular2服务:
getData(source_url: string, parameters: Parameter[]): Observable<any[]> {
let headers = new Headers({ 'X-Requested-With': 'XMLHttpRequest' });
let options = new RequestOptions({ headers: headers });
if (parameters.length > 0) {
let params: URLSearchParams = new URLSearchParams();
for (var index = 0; index < parameters.length; index++) {
params.set(parameters[index].name, parameters[index].value);
}
return this.http.get(source_url, { search: params, headers: headers })
.map(this.extractData)
.catch(this.handleError);
}
else {
return this.http.get(source_url, { headers: headers })
.map(this.extractData)
.catch(this.handleError);
}
}
extracting received response:
private extractData(response: Response) {
let body: any;
let contentType = response.headers.get('content-type');
console.log(contentType);
if (contentType.includes('application/json')){
body = response.json();
}
if (contentType.includes('text/csv')) {
let buffer: any = [];
buffer.push(response._body);
let blob = new Blob(buffer, { type: 'text/csv' });
return blob;
}
if (contentType.includes('application/pdf')) {
return response;
}
return body.data || {};
}
保存对角度组件中文件的响应:
this.myCommonService.getData(actionUrl, params)
.subscribe(data => {
var link = document.createElement('a');
document.body.appendChild(link);
link.style = 'display: none';
let mediaType = 'application/pdf';
let buff = data.arrayBuffer();
let blob = new Blob(buff, { type: mediaType });
let url = window.URL.createObjectURL(blob);
console.log(url);
link.href = url;
link.download = 'mailedletterhistory_' + this.currentLetterBatchID + '.pdf';
link.click();
window.URL.revokeObjectURL(url);
},
error => this.errorMessage = <any>error, () => function () {
} ());
在上面的方法中,数据是响应并且具有带有pdf数据的_body。但下载的文件没有内容(页面为空白)。
有什么想法吗?