【问题标题】:Angular 4 download file from URL从 URL 下载 Angular 4 文件
【发布时间】:2018-05-10 20:11:50
【问题描述】:

我正在使用 firebase,我将图像存储在我的 firebase 存储中,然后在视图上显示这些图像,每个图像都有一个按钮,这个想法是当用户按下按钮时下载图像,我该怎么做,到目前为止,我还没有找到使用角度的方法来做到这一点,在图像对象上,我存储了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>

【问题讨论】:

    标签: angular firebase firebase-storage


    【解决方案1】:

    以防万一其他人在这里遇到同样的问题,我发布了答案,到目前为止,这是使用 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);
            });
          }
    

    【讨论】:

    • 我尝试了上面的代码,但是它在'firebasestorage.googleapis.com/v0/b/…............. .........................' 来自原点 'localhost:4200' 已被 CORS 策略阻止:请求标头字段 access-control-allow-origin预检响应中的 Access-Control-Allow-Headers 不允许。
    【解决方案2】:

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

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

    使用 npm 安装 FileSaver

    npm install --save file-saver
    

    安装打字稿类型

    npm install @types/file-saver --save-dev
    

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

    import { saveAs } from 'file-saver';
    

    然后调用

    saveAs(url, filename);
    

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

    【讨论】:

    • 这些步骤没有为我下载文件。它只是在另一个选项卡中打开文件
    【解决方案3】:

    你可以创建一个这样的按钮

    <a [href]="image.downloadUrl" download></a>
    

    【讨论】:

    • 不,在这种情况下仍然有动作,在另一个标签中打开图像
    • 我刚刚在我的项目中尝试过这个并且工作了。您可以发布其余的代码吗?你把 a 标签放在哪里了?
    • 我正在检查为什么您的代码对我不起作用,而对您起作用,发现“a”元素上的下载属性仅适用于谷歌浏览器,但在 Firefox 中不起作用,那s 为什么在 firefox 上发送到新标签,所以您可能必须使用 google chrome 或任何其他浏览器。
    【解决方案4】:

    尝试:

    download(url, downloadName) {
        leta = document.createElement("a");
        document.body.appendChild(a);
        a.href = url;
        a.download = downloadName;
        a.click();
        document.body.removeChild(a);
      }
    

    【讨论】:

    • 不,只需在新标签页中打开图片即可。
    • 在 a.download 中,取一个带有扩展名的名称,例如“img.png”jsfiddle.net/8japas6a/1
    • 图片的名字上已经有扩展名了,但还是有同样的动作,只是在另一个窗口打开图片。
    【解决方案5】:

    您可以像这样以角度下载 xml 文件:-

    exportXml(license: any) {
        this.licenseService
              .getEncryptLicense(license.LFDNR)
              .subscribe((res: any) => {
                this.downloadFile(
                  res[0].LICENSE_DATA,
                  `${license.TYPE}.xml`,
                  "text/xml"
                );
              });
          }
    
          downloadFile(content: any, fileName: any, contentType: any) {
            const a = document.createElement("a");
            const file = new Blob([content], { type: contentType });
            a.href = URL.createObjectURL(file);
            a.download = fileName;
            a.click();
          }
    

    【讨论】:

      【解决方案6】:
      import * as fs from 'file-saver';
         
       downloadFile(url) {
                  var filename = url.split('/').pop();
                  try {
                      fs.saveAs(url, filename);
                  }
                  catch (e) {
                      console.log(e)
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2018-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        • 2018-10-06
        • 2020-06-02
        • 1970-01-01
        相关资源
        最近更新 更多