角度: 如何从 HttpClient 下载文件?

我需要从我的后端下载一个 Excel,它返回一个文件。

当我执行请求时,我得到错误:

TypeError: 您在预期流的位置提供了“未定义” 可以提供可观察的、允诺的、数组的或可迭代的。

我的代码是:

this.http.get(`${environment.apiUrl}/...`)
.subscribe(response => this.downloadFile(response, "application/ms-excel"));

我试图获得和地图(...) ,但没有工作。

详情: 角度5.2

参考文献:

import { HttpClient } from '@angular/common/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';

内容-回应类别:

Content-Type: application/ms-excel

怎么了?

212003 次浏览

试试这样:

类型: application/ms-excel

/**
*  used to get file from server
*/


this.http.get(`${environment.apiUrl}`,{
responseType: 'arraybuffer',headers:headers}
).subscribe(response => this.downLoadFile(response, "application/ms-excel"));




/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
let blob = new Blob([data], { type: type});
let url = window.URL.createObjectURL(blob);
let pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert( 'Please disable your Pop-up blocker and try again.');
}
}

从后端返回带文件类型的 Blob。以下函数将接受任何文件类型和弹出下载窗口:

downloadFile(route: string, filename: string = null): void{


const baseUrl = 'http://myserver/index.php/api';
const token = 'my JWT';
const headers = new HttpHeaders().set('authorization','Bearer '+token);
this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe(
(response: any) =>{
let dataType = response.type;
let binaryData = [];
binaryData.push(response);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType}));
if (filename)
downloadLink.setAttribute('download', filename);
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}

我花了很多时间寻找这个问题的答案: 如何从我的用 Node.js 写的 API 休息服务器下载一个简单的图片到一个 Angular 组件应用程序中,我终于在这个 web 角形 HttpClient Blob中找到了一个漂亮的答案。基本上包括:

静止的 API Node.js:

   /* After routing the path you want ..*/
public getImage( req: Request, res: Response) {


// Check if file exist...
if (!req.params.file) {
return res.status(httpStatus.badRequest).json({
ok: false,
msg: 'File param not found.'
})
}
const absfile = path.join(STORE_ROOT_DIR,IMAGES_DIR, req.params.file);


if (!fs.existsSync(absfile)) {
return res.status(httpStatus.badRequest).json({
ok: false,
msg: 'File name not found on server.'
})
}
res.sendFile(path.resolve(absfile));
}

Angular 6测试组件服务(EmployeeService) :

  downloadPhoto( name: string) : Observable<Blob> {
const url = environment.api_url + '/storer/employee/image/' + name;


return this.http.get(url, { responseType: 'blob' })
.pipe(
takeWhile( () => this.alive),
filter ( image => !!image));
}

模板

 <img [src]="" class="custom-photo" #photo>

组件订户和使用:

@ViewChild('photo') image: ElementRef;


public LoadPhoto( name: string) {
this._employeeService.downloadPhoto(name)
.subscribe( image => {
const url= window.URL.createObjectURL(image);
this.image.nativeElement.src= url;
}, error => {
console.log('error downloading: ', error);
})
}

我在这里结束时,搜索“ rxjs 下载文件使用后”。

这是我的最终产品。它使用服务器响应中给出的文件名和类型。

import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';


downloadPost(url: string, data: any) {
return ajax({
url: url,
method: 'POST',
responseType: 'blob',
body: data,
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain, */*',
'Cache-Control': 'no-cache',
}
}).pipe(
map(handleDownloadSuccess),
);
}




handleDownloadSuccess(response: AjaxResponse) {
const downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(response.response);


const disposition = response.xhr.getResponseHeader('Content-Disposition');
if (disposition) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
const filename = matches[1].replace(/['"]/g, '');
downloadLink.setAttribute('download', filename);
}
}


document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}

我花了一些时间来实现其他的响应,比如 我使用角8(测试到13)。我最终得到了以下代码(深受 Hasan 的启发)。

注意,对于要设置的名称,头 Access-Control-Expose-Headers必须包括 Content-Disposition。设置为 django RF:

http_response = HttpResponse(package, content_type='application/javascript')
http_response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
http_response['Access-Control-Expose-Headers'] = "Content-Disposition"

角度:

  // component.ts
// getFileName not necessary, you can just set this as a string if you wish
getFileName(response: HttpResponse<Blob>) {
let filename: string;
try {
const contentDisposition: string = response.headers.get('content-disposition');
const r = /(?:filename=")(.+)(?:;")/
filename = r.exec(contentDisposition)[1];
}
catch (e) {
filename = 'myfile.txt'
}
return filename
}


  

downloadFile() {
this._fileService.downloadFile(this.file.uuid)
.subscribe(
(response: HttpResponse<Blob>) => {
let filename: string = this.getFileName(response)
let binaryData = [];
binaryData.push(response.body);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'blob' }));
downloadLink.setAttribute('download', filename);
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}


// service.ts
downloadFile(uuid: string) {
return this._http.get<Blob>(`${environment.apiUrl}/api/v1/file/${uuid}/package/`, { observe: 'response', responseType: 'blob' as 'json' })
}


使用 Blob作为 img的来源:

模板:

<img [src]="url">

组成部分:

 public url : SafeResourceUrl;


constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
this.getImage('/api/image.jpg').subscribe(x => this.url = x)
}


public getImage(url: string): Observable<SafeResourceUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(
map(x => {
const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
}),
);
}

关于 相信存储值的进一步参考

使用来自 API 的 Blob 输出(Excel 文件)

调整@gabrielrincon 的回答

downloadExcel(): void {
const payload = {
order: 'test',
};


this.service.downloadExcel(payload)
.subscribe((res: any) => {
this.blobToFile(res, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Export.xlsx");
});}

Blob 到文件的公共函数

blobToFile(data: any, type: string, fileName: string) {
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
const blob = new Blob([data], { type: type });
const url = window.URL.createObjectURL(blob);
a.href = url; a.download = fileName; a.click();
window.URL.revokeObjectURL(url);}

在 blob to file 函数中,我们期望第一个参数作为 blob 数据、文件类型和传递文件名(包括扩展名1)。我们正在创建一个 html 标记元素2。然后在 html 3中添加元素。然后隐藏标签元素4。然后用文件和类型5创建新的 blob 对象。我们将把 blob 对象转换为 URL 6。然后将该 URL 附加到标记7的 href 属性。我们打开我们的网址在窗口,所以它将下载

也许我迟到了,但是@Hasan 的最后一个回答非常棒。

我只是在这里做了一些小的改动(这里不接受移除的头) ,然后就获得了成功。

downloadFile(route: string, filename: string = null): void {
// const baseUrl = 'http://myserver/index.php/api';
this.http.get(route, { responseType: 'blob' }).subscribe(
(response: any) => {
let dataType = response.type;
let binaryData = [];
binaryData.push(response);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: dataType }));
if (filename) {
downloadLink.setAttribute('download', filename);
}
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}

保持简单,我被所有复杂的解决方案所震惊。

如果您的后端返回 attachment标志和 Content-Disposition中的 filename属性,您可以简单地进行这个 javascript 调用。

window.location = `${environment.apiUrl}/...`;

浏览器将在不更改当前页面的情况下下载该文件。