我已经从不同的博客和SO中获取了以下代码,因为我找不到执行此操作的任何教程。
我要做的是使用angular和typescript从REST API下载文件。我没有对api的访问权限(只有url之类的“ http:// ...”,仅此而已。
这是我的打字稿代码:
//Downloading File
// may be located in any component
let options = {
responseType: ResponseContentType.Blob //This has compilation error. Cannot recognize ResponseContentType.Blob
}
// pass options to request
this.http.get(url, options)
let type = "my/mime";
// download the file - retrieve observable
this.http.get(url, options).map((res: Body) => new Blob([res.blob()], { type: type }));
public downloadAttachment(attachment: MediaDownloadFileDto): void {
this.myDownloadService.downloadFile(downloadUrl, mimeType).subscribe((fileBlob: Blob) => {
fileSaver.saveAs(fileBlob, attachment.filename);
}, (message: string) => {
// error handling...
});
}
// may be located in any service:
public downloadFile(url: string, type: string): Observable<Blob> {
let options = {
responseType: ResponseContentType.Blob
};
return this.http.get(url, options).map((res: Body) => new Blob([res.blob()], { type: type }));
}
这是我正在使用的HTML按钮:
<button class="nui-button nui-button--alt download" (click)="downloadFile(url,options)">Download Template</button>
谢谢
答案 0 :(得分:0)
您可以简单地使用HTML download
属性。
尝试一下:
<a href="https://some-rest-api.com/some-file.mp4" download>