在 Angular 中下载一个文件 2
Download a file in Angular 2
我想在 Angular 2 中下载一个 pdf 格式的文件,我正在使用 FileSaver.js
将文件另存为 pdf。
(response) => {
var mediaType = 'application/pdf';
let pdfContent = response["_body"];
var blob = new Blob([pdfContent], {type: mediaType});
var filename = 'test.pdf';
//setTimeout(FileSaver.saveAs(blob, filename),10000); //Tried this but no result
// FileSaver.saveAs(blob(), "docitt-report-" + documentNo + ".pdf"); //tried this too
},
但是下载的pdf文件是空的,我想可能是资源占用了时间所以我尝试了setTimeout
,但还是没有用。虽然响应中有数据,但我可以在控制台中看到 response._body
。
让我知道哪里出错了。
import 'rxjs/Rx' ;
this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
error => console.log("Error downloading the file."),
() => console.info("OK");
When the request is ready it will call the function "downloadFile" that is defined as follows
downloadFile(data: Response){
var blob = new Blob([data], { type: 'text/csv' });
var url= window.URL.createObjectURL(blob);
window.open(url);
}
我成功了,下面是我的回答:
downloadDocument(docId){
const headers = new Headers({responseType:ResponseContentType.Blob});
headers.append('authorization','Bearer '+token);
this.http.get(url,{headers:headers,responseType:ResponseContentType.Blob}).subscribe(
(response) => {
FileSaver.saveAs(response.blob(), "Document-" + docId+ ".pdf");
}
);
}
导入 FilSaver
import * as FileSaver from 'file-saver';
我想在 Angular 2 中下载一个 pdf 格式的文件,我正在使用 FileSaver.js
将文件另存为 pdf。
(response) => {
var mediaType = 'application/pdf';
let pdfContent = response["_body"];
var blob = new Blob([pdfContent], {type: mediaType});
var filename = 'test.pdf';
//setTimeout(FileSaver.saveAs(blob, filename),10000); //Tried this but no result
// FileSaver.saveAs(blob(), "docitt-report-" + documentNo + ".pdf"); //tried this too
},
但是下载的pdf文件是空的,我想可能是资源占用了时间所以我尝试了setTimeout
,但还是没有用。虽然响应中有数据,但我可以在控制台中看到 response._body
。
让我知道哪里出错了。
import 'rxjs/Rx' ;
this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
error => console.log("Error downloading the file."),
() => console.info("OK");
When the request is ready it will call the function "downloadFile" that is defined as follows
downloadFile(data: Response){
var blob = new Blob([data], { type: 'text/csv' });
var url= window.URL.createObjectURL(blob);
window.open(url);
}
我成功了,下面是我的回答:
downloadDocument(docId){
const headers = new Headers({responseType:ResponseContentType.Blob});
headers.append('authorization','Bearer '+token);
this.http.get(url,{headers:headers,responseType:ResponseContentType.Blob}).subscribe(
(response) => {
FileSaver.saveAs(response.blob(), "Document-" + docId+ ".pdf");
}
);
}
导入 FilSaver
import * as FileSaver from 'file-saver';