angular - 如何从api保存文件
问题描述
我是 Angular 新手,我需要知道如何将我的 API 中的文件保存在用户计算机上。在我的 API 中,我downloadChapter
在 /download/chapter/{id} 上有带有方法的 DownloadController。当我从 Chrome 调用此方法时,我的计算机刚开始下载章节文件 - 没关系。当我从我的 DownloadService 中以角度调用此方法时,我在控制台中收到错误:ERROR OK。
我的下载章节方法:
downloadChapter(id: number): Observable<Blob> {
return this.http
.get<Blob>(`${this.basicPath}/chapter/${id}`)
.pipe(
tap((res) => {
console.log(`response: ${res}`);
},
(e) => {
console.log(`error: ${e} - ???`);
}, () => {
console.log('win!');
}),
);
}
在 API 响应中:
200 OK OK,URL [file:/Users/lukasz/Workspace/Inz/api/booky/uploads/1/6:Solaris%20-%20Maly%20Apokryf.mp3],[Content-Disposition:"attachment;filename=6 :Solaris%20-%20Maly%20Apokryf.mp3", Content-Type:"audio/mpeg", Content-Length:"97857000"]
如何解决?我只想将文件保存在用户计算机上。
解决方案
这是一个从 restful api 下载文件的 Angular 6 示例:
安装文件保护程序:
npm install file-saver --save
import { HttpClient } from '@angular/common/http';
import { saveAs } from 'file-saver';
.
.
.
constructor(private http: HttpClient) { }
download() {
this.http.get('/download/chapter/{id}', {responseType:'blob', observe: 'response'}).subscribe(
(data : any)=>{
saveAs(data.body, 'yourfilename.ext');
},
(err : HttpErrorResponse)=>{
console.error('download failed:', err);
});
}
.
.
.
推荐阅读
- javascript - 您将如何提取 2 个数字并将它们存储到字符串中的单独变量中
- node.js - 似乎无法自动完成在 WebStorm 中工作
- django - 在 django 中执行“python manage.py runserver”时出现问题
- javascript - 在嵌套对象中查找对象:超出最大调用堆栈大小
- ios - 从 NSDictionary 获取值时出错
- surface - 从一组 3D 点生成 OPEN 曲面网格
- git - Git 获取用户名和密码
- css - 如何在有序列表的项目之间添加空行?
- python - Terminate a Python script after a time period
- python-3.x - 遍历文件夹时如何跳过整个文件?