从 URL 下载 Angular 4 文件

Mig*_*ias 0 firebase firebase-storage angular

我正在使用 firebase,我将图像存储在我的 firebase 存储上,然后在视图上显示这些图像,每个图像都有一个按钮,这个想法是当用户按下按钮时下载图像,到目前为止我该怎么做我一直无法找到使用 angular 的方法,在图像对象上,我存储了downloadUrl上传图像时提供的火库,我想使用该 URL 下载图像

成分

    <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>
Run Code Online (Sandbox Code Playgroud)

Mig*_*ias 5

以防万一其他人有同样的问题,我在这里发布了答案,到目前为止,这是使用 firebase 存储实现这一目标的最佳方法。在函数userSettings中只是一个字符串(当前用户登录的 id),filename是要从 firebase 存储下载的文件的名称

下载功能

  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);
        });
      }
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 5

@Miguel 创建的答案的替代方法是使用 FileSaver。

当我使用 AWS 而 OP 使用 Firebase 时,过程是相同的。AWS Storage 和 Firebase 都会返回必须下载的文件的 URL。为了下载 URL 的内容,我使用了 FileSave。

使用 npm安装FileSaver

npm install --save file-saver
Run Code Online (Sandbox Code Playgroud)

安装 typescript 类型

npm install @types/file-saver --save-dev
Run Code Online (Sandbox Code Playgroud)

然后在你的 Angular ts 文件中导入 filesave

import { saveAs } from 'file-saver';
Run Code Online (Sandbox Code Playgroud)

然后打电话

saveAs(url, filename);
Run Code Online (Sandbox Code Playgroud)

这与接受的答案相同,但工作量更少,并且代码库是通过一堆额外的好用函数来维护的。