2017-02-15 37 views
1

我正在创建一个应用程序来浏览和下载电话录音。如何用Angular 2触发文件下载?

此应用程序的一部分是一个用* ngFor填充以显示录制内容和相关信息的表格。表格中的每一行还有一个复选框,用于标记要下载的记录。我已经到了可以将console.log链接指向我正在使用的测试mp3的地步,但我无法弄清楚如何实际触发所述mp3的下载。

我真的很希望能够使用Typescript和不使用jQuery来做到这一点。

<table> 
     <thead> 
      <tr> 
       <th> 
        <input type="checkbox" [checked]="isAllChecked()" (change)="checkAll($event)"> </th> 
       <th>Date</th> 
       <th>Time</th> 
       <th>Duration</th> 
       <th>Calling Number</th> 
       <th>Called Number</th> 
       <th> </th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr *ngFor="let entry of recordingsList"> 
       <td> 
        <input type="checkbox" [(ngModel)]="entry.isSelected"> </td> 
       <td>{{entry.date}}</td> 
       <td>{{entry.time}}</td> 
       <td>{{entry.duration}}</td> 
       <td>{{entry.callingNumber}}</td> 
       <td>{{entry.calledNumber}}</td> 
       <td> 
        <button (click)="openPlayer(entry)" class="play-button"><i class="material-icons">play_arrow</i></button> 
       </td> 
      </tr> 
     </tbody> 
    </table> 

-

// Download selected recordings 

    downloadSelected() { 
     let isSelected = this.recordingsList.filter(x => x.isSelected); 
     isSelected.forEach(x => console.log(x.audio)); 
    } 

-

任何援助不胜感激。

+0

[Anchor element](https: //developer.mozilla.org/en/docs/Web/HTML/Element/a)有一个'download'属性。 –

回答

1

直接回答这个问题,你可以为每个链接打开新的标签页:

downloadSelected() { 
     let isSelected = this.recordingsList.filter(x => x.isSelected); 
     isSelected.forEach(x => window.open(x.audio, '_blank')); 
    } 

然而,这是不是与多个选项卡打开了似地方面的用户体验优雅。所以我建议你创建一个特殊的url(例如:example.com/bulk-download?ids=1,34,56),它可以创建带有选定文件的zip文件夹,并允许用户下载

+0

谢谢你的帮助!但是,有两个问题阻止了这个完全满足我的需求。它会在新窗口中打开选定的mp3,而当用户单击下载按钮时,我需要该文件开始下载。另外,这不会打开所有选定的录音。它似乎只是打开第一个。 –

+0

从技术上讲,您可以创建多个锚点元素并触发点击事件。但是,由于浏览器的限制,这是不可靠的,并且它不是角度方式。所以,正确的解决方案是在后端创建压缩文件。 –

+0

是的,这似乎不是一个非常干净的解决方案。我希望我可以在Angular中做到这一点,但它看起来越来越像是不可能的,我将需要我的后端开发人员创建所选文件的zip文件和一个链接,以便我可以href到。 :( –