-1

Sir, I have some problem when I download file by URL.

My code snippet like this.

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() {

}

I'm going to download when the doDownload() function execute. How to download file by URL in angular 7?

Opal
  • 81,889
  • 28
  • 189
  • 210

1 Answers1

1

See this 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>
Muhammet Can TONBUL
  • 3,217
  • 3
  • 25
  • 37