Tel Map

Blog

Angular 5 HttpClient File Download with Authentication

18 Antworten auf „Angular 5 HttpClient File Download with Authentication“

  1. Thank you for this. You saved the day. Although my http get is without and only with ‚blob‘. There is some angular 5 issue with this.

    Whole service method:

    getShipmentAttachment(shipmentId: number, attachmentId: number): Observable {

    let url: string = this.getFullUrl(/api/v1/shipments/${shipmentId}/attachments/${attachmentId});
    let headers: HttpHeaders = new HttpHeaders().set(‚Authorization‘, this.token);

    return this._httpClient.get(url, {
    headers: headers,
    responseType: ‚blob‘ // very important that this is set
    })
    .pipe(
    catchError(this.handleError)
    );
    }

  2. Rob

    This won’t work at all in Angular 6 typescript.
    Also why are you using promises when Angular 2 + has Observables ?

    My service function:
    getEvidenceFile(id: number, getFileContent: boolean) {

    return this.http.get(environment.baseUrl + ‚upload‘ + ‚/‘ + id + ‚,‘ + getFileContent, {responseType: ‚blob‘ as ‚json‘})
    .map(res => res);
    }

    My component function called from the selected item of a dropdown…
    dropDownValue(event: any) {

    // const blob = await this.callService.getEvidenceFile(event.target.value, true);
    // const url = window.URL.createObjectURL(blob);

    this.callService.getEvidenceFile(event.target.value, true).subscribe(data => {

    var binaryData = [];
    binaryData.push(data);
    var downloadLink = document.createElement(‚a‘);
    downloadLink.href = window.URL.createObjectURL(new Blob(binaryData));
    document.body.appendChild(downloadLink);
    downloadLink.click();

    });
    }

    [ts] Property ‚URL‘ does not exist on type ‚ (this: Observable , windowBoundaries: Observable) => Observable<Observable>‘.

  3. tatsu

    createObjectURL went into deprecation 7 years ago and has been effectively deprecated 2 years ago this guide has been unusable for two years. please update it.

    1. Hi tatsu,
      Do you have any source for this? I looked at the Mozilla documentation for URL.createObjectURL and there is no sign of a deprecation: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL with full support in all major browsers.

      There seems to be a change however, when using a MediaStream with an HTMLMediaElement (like Video) which used to utilize URL.createObjectURL, but doesn’t any more : https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
      Maybe this is what you are referring to?

  4. Jack

    This is great, even years later. Had exactly this scenario, but most examples have you use href to api call which doesn’t work in real authentication scenarios. Thanks!

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert