[Fixed] Angular 4 download file from URL

Issue

I´m working with firebase, im storing images on my firebase storage and then displaying those images on the view, each image has a button that the idea is when the user press the button download the image, how can i do it, so far i haven´t been able to find i way to do this using angular, on the image object i store the downloadUrl that fire storage give when i upload the image and i want to use that URL to download the image

Component

    <div class="wrapper-gallery" id="photos_container">
      <div class="mix col-xs-12 col-sm-4 col-md-3 item-photo" *ngFor="let photo of couplePhotos | async | sortByFavorites: sortBy | sortByTime: sortBy">
        <div class="photo">
          <img class="img-fluid" src="{{photo.data.photo_url}}" alt="{{photo.data.name}}">
          <button class="delete" (click)="deletePhoto(photo.id, photo.data.name)"><span class="icon-cross"></span></button>
          <a class="search zoom" data-fancybox="wedding" href="{{photo.data.photo_url}}"><span class="icon-search"></span></a>
          <button class="star" [ngClass]="{'start-on': photo.data.favorite == true}" (click)="toggleFavorite(photo.id, photo)"><span class="icon-star-full"></span></button>
          <button class="download" (click)="downloadImg()"><span class="icon-download"></span></button>
          <a [href]="photo.data.photo_url" download></a>
        </div>
      </div>
    </div>

Solution

Just in case some else have the same problem here i post the answer, so far this is the best way to make this using the firebase storage. in the function userSettings is just a string (id of the current user login) and filename is the name of the file to download from the firebase storage

Download function

  public downloadFile(userSettings: string, filename): void {
    this.storageRef.ref().child(`weddingDreamPhotos/${userSettings}/${filename}`)
      .getDownloadURL().then((url) => {
          const xhr = new XMLHttpRequest();
          xhr.responseType = 'blob';
          xhr.onload = (event) => {
            /* Create a new Blob object using the response
            *  data of the onload object.
            */
            const blob = new Blob([xhr.response], { type: 'image/jpg' });
            const a: any = document.createElement('a');
            a.style = 'display: none';
            document.body.appendChild(a);
            const url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
          };
          xhr.open('GET', url);
          xhr.send();
        }).catch(function(error) {
          // Handle any errors
          console.log(error);
        });
      }

Leave a Reply

(*) Required, Your email will not be published