使用httpClient和Angular下载.tar文件

时间:2019-08-26 11:34:11

标签: angular httpclient tar

我正在尝试使用Angular中的HttpClient下载.tar文件。 我首先尝试的是正常请求。与我使用普通文本文件相同的过程,但是没有用。它返回http故障响应。

export class ApiService {

  constructor(private http: HttpClient) { }
  public getData(){
    return this.http.get(`file.tar`);
  }

我尝试的下一件事是使用下载Excel文件的方式,因为.tar包含csv文件:

export class ApiService {


  downloadExcel() {
    const options = new RequestOptions({
              responseType: ResponseContentType.Blob,
              headers: new Headers({ 'Accept': 'application/vnd.ms-excel' })
          });

    this.httpClient.get('file.tar', options)
             .catch(errorResponse => Observable.throw(errorResponse.json()))
             .map((response) => { 
                   if (response instanceof Response) {
                      return response.blob();
                   }
                   return response;
              })
             .subscribe(data => saveAs(data, 'file.tar'),
                        error => console.log(error));

  }   
}

这返回了更多的http故障响应,并且我在导入方面也遇到了问题

例如

  

找不到名称“ RequestOptions”

     

“可观察类型不存在属性“捕获””

     

找不到名称“ saveAs”

我的进口是:

mport { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable, EMPTY, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

使用angular和httpClient下载.tar文件的正确方法是什么?关于我做错了什么的解释也很好。

2 个答案:

答案 0 :(得分:0)

您可以使用文件保护程序包https://github.com/eligrey/FileSaver.js/

export class ApiService {

downloadExcel() {
    const headers = new HttpHeaders({
      responseType: 'blob',
      headers: 'application/tar'
    });

    this.http
      .get('file.tar', { headers })
      .pipe(
        catchError(errorResponse => Observable.throw(errorResponse.json())),
        map(response => {
          if (response instanceof Response) {
            return response.blob();
          }
          return response;
        })
      )
      .subscribe(
        data => {
          const blob = new Blob(data, {
            type: 'application/tar;charset=utf-8'
          });
          FileSaver.saveAs(blob, 'file.tar');
        },
        error => console.log(error)
      );
  }   
}

修改 您必须使用.pipe()方法。

答案 1 :(得分:0)

catch 中没有任何属性为 Observable 。相反,您应该在 catchError 方法内使用 rxjs/operators 中的 pipe() 。 使用 responseType: "blob" 代替 responseType: ResponseContentType.Blob 。 您应该使用 Content-Type 标头,而不是 Accept 标头。

downloadExcel() {

    const options = { 
        responseType: "blob",  
        headers: new HttpHeaders({ 'Content-Type': 'application/vnd.ms-excel' }) 
    };

    this.httpClient.get('file.tar', options).pipe(
            catchError(this.errorHandler('error in downloading file.'))
        ).subscribe((res: any) => {

            saveAs(res, 'file.tar');
    });
}

private errorHandler() {

    console.error(err)
}