首页 > 解决方案 > 如何使用新的 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());

标签: angularfilegetblobhttpclient

解决方案


尝试window.open(url)

如果类型将是浏览器支持的image等等pdf,它将打开,否则下载它。

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.');
 }

推荐阅读