angular - 如何使用新的 HttpClient 下载文件?
问题描述
所以它过去的工作方式是我做了一个“GET”并提供了一个 ID,并且返回的数据我只需要这样做:
const subscription = this.downloadService.downloadFile(id, this.file.folderId).subscribe(data => {
window.location.href = data.url;
subscription.unsubscribe();
});
Chrome 会自动下载文件并留在网站上。
现在我这样做:
const subscription = this.downloadFile(id, folderId).subscribe(data => {
const blob = new Blob([data], { type: 'image' });
const blobUrl = window.URL.createObjectURL(blob);
window.location.href = blobUrl;
subscription.unsubscribe();
});
Chrome 也会开始下载,但它始终是同一个文件,在控制台中看起来像这样:
我尝试将其转换为文件,但“window.location.href”需要一个 URL,而当我将其转换为这样的文件时,我没有该 URL:
const file = new File([blob], name, { lastModified: Date.now(), type: 'image' })
我需要如何处理这些数据以确保将其下载为图像(我尝试下载的始终是图像)?
编辑:显然我的 httpParams 实施错误!这是错误的方法:
const httpParams = new HttpParams();
httpParams.append('action', 'downloadFile');
httpParams.append('fileIds', id.toString());
httpParams.append('currentLibraryFolderId', folderId.toString());
它只通过了一个空的 httpParams。这是正确的方法:
const params = new HttpParams()
.set('action', 'downloadFile')
.set('fileIds', id.toString())
.set('currentLibraryFolderId', folderId.toString());
解决方案
尝试window.open(url)
:
如果类型将是浏览器支持的
image
等等
HTML:
<a (click)="downloadFile(fileData, type)" download>Download File</a>
下载并保存使用FileSaver
:
npm install file-saver --save
import { saveAs } from 'file-saver/FileSaver';
如果您收到回复为arraybuffer
var blob = new Blob([data], { type: type});
var url = window.URL.createObjectURL(blob);
saveAs(blob, filename);
var winOpen = window.open(url);
// If Popup blocked
if (!winOpen || winOpen.closed || typeof winOpen.closed == 'undefined') {
alert( 'Please disable your Pop-up blocker and try again.');
}
推荐阅读
- typescript - 错误:“ObjectBuilder”类型上不存在属性“onChange”
- html - Google Apps 脚本;侧边栏关闭
- vuejs2 - Vuex状态在绑定时将[object Object]插入输入
- python - rtsp 方法设置失败:461 客户端错误
- html - 因此
和其他元素有自己的填充
- php - 获取最多 n 级的 XML 标记和属性
- kotlin - 我如何在 kotlin 中与超类建立一对一的关系
- javascript - 如何替换包含不固定字符的字符串中的某些字符
- c# - XNA/Monogame 中的 Ray 视线
- json - 在 Swift 4 中访问嵌套 JSON 字符串的成员