typescript 如何使用 Angular 5 下载文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51952190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I download file using Angular 5?
提问by thedbogh
When I paste my_example_link
in a browser the file is automatically downloaded in a proper way. However, when I use source code shown below download doesn't work. I would like to download file after clicking download
button. Any ideas what is wrong? I don't get any errors.
当我my_example_link
在浏览器中粘贴时,文件会以正确的方式自动下载。但是,当我使用下面显示的源代码时,下载不起作用。我想在单击download
按钮后下载文件。任何想法有什么问题?我没有收到任何错误。
user.service.ts:
用户服务.ts:
DownloadFiles() {
return this.http.get('my_example_link', {responseType: 'text'});
}
uploader.service.ts:
上传者.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:
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>
回答by Akj
Use arraybuffer
使用数组缓冲区
this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});
To save File:
保存文件:
npm install file-saver --save
import { saveAs } from 'file-saver/FileSaver';
component:
零件:
downLoadFile(data: any, type: string) {
var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
saveAs(blob,"file_name.txt");
window.open(url);
}