Search code examples
angularhttpclienttar

Downloading a .tar file with httpClient and Angular


I am trying to download a .tar file with HttpClient in Angular. What I tried first was a normal request. The same procedure as i would with a normal text file but this didn't work. It returns a http failure response.

export class ApiService {

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

Next thing I tried was using the way of downloading an excel file, as the .tar contains csv files:

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

this returned even more http failure responses and i'm having problems with the imports aswell

for example

Cannot find name 'RequestOptions'

"Property 'catch' does not exist on type 'Observable"

Cannot find name 'saveAs'

my imports are:

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';

What would be the correct way to download a .tar file with angular and httpClient? Some explanation on what I did wrong would be great as well.


Solution

  • You could use file-saver package 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)
          );
      }   
    }
    

    Edit You have to use .pipe() method.