angular - 如何在 Angular cli 中下载文件?
问题描述
下载文件时遇到问题,当我从后端收到响应时,如何下载文件?
错误是当我想获取文件名时
这是我的 .ts :
async download(path: any) {
const { status, headers, body } = await this.studentService.download(path);
const filenames = this.Filename(headers);
const blob = new Blob([body],{type:'application/octet-stream'});
saveAs(blob, filenames);
}
Filename(headers: any) {
let filenames = '';
var RGX_FILENAME = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const contentDisposition = headers.get('Content-Disposition');
const matches = RGX_FILENAME.exec(contentDisposition);
if (matches && matches[1]) {
filenames = matches[1].replace(/['"]/g, '');
}
return filenames;
}
这是我的 .service :
async download(param: any): Promise<any> {
const query = this.paramFile(param);
const result = await this.get(
`${environment.apiUrl}/file/${query}`
);
return result;
}
paramFile(param: any) {
const query = `${param}`;
return query;
}
求你帮忙,截止日期是2小时,所以希望有人能帮助我并指导我完成
解决方案
只需调用您的服务,该服务基本上应该返回字节数组,然后以这种方式将其保存到 blob。您可以根据需要更改类型。
在你的 ts 中:
this.yourservice.downloadFile().subscribe((resp) => {
const fileName = resp.headers.get('filename') ? resp.headers.get('filename') : 'file1_' + new Date();
const data = resp.body;
this.blob = new Blob([data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var downloadUrl = window.URL.createObjectURL(data);
var link = document.createElement('a');
link.href = downloadUrl;
link.download = fileName + '.xlsx';
link.click();
}, error => {
console.log("Error downloading the file!!!");
});
服务代码:
downloadFile() {
const headers = new HttpHeaders()
.set('Accept', 'application/xlsx; charset=utf-8');
const url = `${this.baseUrl}dowmloadxls`;
const params = new HttpParams()
.set("userId", userId);
return this.http.get(url, { params, headers, observe: 'response', responseType: 'blob' });
}
推荐阅读
- xml - XSLT - Nested XML to CSV output
- css - SVG CSS animation after hover off
- vba - Excel VBA - 在工作簿中禁用复制/剪切粘贴
- xamarin - 通过多个视图模型进行 Mvvm 交叉导航
- php - 使用 php DOMElement 和值的开头获取特定输出?
- react-native - 安卓的绝对位置
- c - libgit2 如何成功提交文件?
- ios - SwiftSoup cocoapods 仅安装且仅安装 1.4 版,而不是 1.5
- javascript - 为特定文件添加一个新行的 Gulp 任务
- elasticsearch - Filebeat 没有将日志发送到 logstash