Angular2 >

Angular2でファイルダウンロード

HTML

<button (click)="onClickDownload()">ダウンロード</button>
<a #downloadLink [href]="downloadUrl" [download]="downloadFile" style="display:none;" >ダウンロード</a>

Component

import { Component, OnInit, ElementRef, ViewChild, Renderer2 } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-download1',
  templateUrl: './download1.component.html',
  styleUrls: ['./download1.component.css']
})
export class Download1Component implements OnInit {

  @ViewChild('downloadLink') downloadLink: ElementRef;

  downloadUrl = null;
  downloadFile = ''; 

  constructor(private el: ElementRef, private renderer: Renderer2, private sanitizer: DomSanitizer) { } 

  ngOnInit() {
  }

  onClickDownload() {

    const data = 'テストデータです';
    const contentType = 'plain/text';

    const fileName = 'test.txt';
    const blob = new Blob([data], { type: contentType }); 

    if (window.navigator.msSaveBlob) {
        // IE
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
 
       // Other
        const url = window.URL.createObjectURL(blob);

        // そのままWindowOpenするとダウンロードファイル名が付けられないので
        // ダウンロード用リンクの href と download属性をセットしてダウンロードさせる。
        //window.open(url);
        this.downloadUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
        this.downloadFile = fileName;

        // すぐにクリックすると href が設定される前に、ダウンロードが行われる時があるので 0.1秒だけ遅延させる
        const component = this;
        setTimeout(function(){
            // const event = new MouseEvent('click', {bubbles: true});
            // this.renderer.invokeElementMethod(this.downloadLink.nativeElement, 'dispatchEvent', [event]);
            // component.renderer.invokeElementMethod(this.downloadLink.nativeElement, 'dispatchEvent', [event]);
            component.downloadLink.nativeElement.click();
        }, 100);
    }   
  }

}

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2018-02-06 (火) 22:42:50 (2263d)