当我在浏览器中粘贴my_example_link
时,文件会以适当的方式自动下载。但是,当我使用下面显示的源代码时,下载不起作用。我想在点击download
按钮后下载文件。任何想法有什么问题吗?我没有任何错误。
user.service.ts:
DownloadFiles() {
return this.http.get('my_example_link', {responseType: 'text'});
}
uploader.service.ts:
DownloadFile(){
this.userService.DownloadFiles()
.subscribe(
(data) => this.downloadFile2(data)), // console.log(data),
(error) => console.log("Error downloading the file."),
() => console.info("OK");
}
downloadFile2(data: Response){
var blob = new Blob([data], { type: 'text/csv' });
var url= window.URL.createObjectURL(blob);
window.open(url);
}
something.component.html:
<li class="nav-item" *ngIf="isCloud()">
<a (click)="this.UploaderService.DownloadFile()" download="file23.txt" style='cursor: pointer;' class="nav-link" target="_blank">
<i class="nc-icon nc-basket"></i> Download
</a>
</li>
答案 0 :(得分:4)
使用 arraybuffer
this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});
要保存文件:
npm install file-saver --save
import { saveAs } from 'file-saver/FileSaver';
组件:
downLoadFile(data: any, type: string) {
var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
saveAs(blob,"anyName.txt");
window.open(url);
}