Angular 7文件下载

时间:2019-03-19 14:05:15

标签: angular file

先生,我通过URL下载文件时遇到了一些问题。

我的代码段是这样的。

ngOnInit() {
    this.items = [
      {label: '1.txt', value: 'https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg'},
      {label: '2.txt', value: 'https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg'},
      {label: '3.txt', value: 'https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg'},
    ];
    this.selectedItem = this.items[0].value;
  }

doDownload() {

}

我将在执行doDownload()函数时进行下载。 如何在angular 7中通过URL下载文件?

1 个答案:

答案 0 :(得分:1)

查看此https://stackblitz.com/edit/angular-ljqvum

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular';
  items = [];
  selectedItem: any;
  ngOnInit() {
    this.items = [
      { label: '1.txt', value: 'https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg' },
      { label: '2.txt', value: 'https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg' },
      { label: '3.txt', value: 'https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg' }
    ];
    this.selectedItem = this.items[0].value;
  }

  doDownload(value) {
    var link = document.createElement('a');
    link.href = value;
    link.download = 'Download.jpg';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
 <li *ngFor="let img of items">
<img [src]="img.value" alt="Smiley face" height="42" width="42" (click)="doDownload(img.value)">
   </li>