我有一个按钮定义为:
<button pButton type="button" label="Download" data-icon="fa-cloud-download" (click)="download()"></button>
下载方法委托给服务的地方,服务使用post方法调用api:
download(model:GlobalModel) {
let downloadURL = base + "rest/process/download";
let body = JSON.stringify(model);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
this.http.post('http://localhost:48080/rest/process/download',body,options)
.toPromise()
.then(
response => {
console.log(response);
var mediaType = 'application/zip';
var blob = new Blob([response.blob()],{type: mediaType});
var filename = 'project.zip';
saveAs(blob,filename);//FileSaver.js libray
});
}
但到目前为止还没有实现blob()方法,并且还有其他使用_body的答案,但是有一个打字稿错误,比如“_body is private”.
浏览器显示下载窗口,但是当我下载文件时已损坏且无法打开它(我检查邮递员并且文件是从服务器生成的).
我怎样才能正确下载文件?…如果不可能,有可用的解决方法吗?
这是一个工作的例子
https://stackoverflow.com/a/42992377/3752172
https://stackoverflow.com/a/42992377/3752172
将控制器修改为POST:
[HttpPost("realisationsFilterExcel")]
public FileResult exportExcell([FromBody] FilterRealisation filter)
{
var contentType = "application/octet-stream";
HttpContext.Response.ContentType = contentType;
PaginationSet<RealisationReportviewmodel> itemsPage = _realisationRepository.GetRealisationReportFilter(filter,User);
RealisationsReportExcell reportExcell = new RealisationsReportExcell();
var filedata = reportExcell.GetReport(itemsPage);
FileContentResult result = new FileContentResult(filedata,contentType)
{
FileDownloadName = "report.xlsx"
};
return result;
}
需要FileSaver作为dep:
npm install file-saver --save npm install @types/file-saver --save
将方法DownloadComponent angular2修改为POST
@input() filter: any;
public downloadFilePost() {
this.http.post(this.api,this.filter,{ responseType: ResponseContentType.Blob })
.subscribe(
(response: any) => {
let blob = response.blob();
let filename = 'report.xlsx';
FileSaver.saveAs(blob,filename);
});
}
运用
<download-btn [filter]="myFilter" api="api/realisations/realisationsFilterExcel"></download-btn>