Angular2 >

Angular2でFile APIを利用する

HTML

<input type="file" id="file1" (change)="onFileSelect($event)" >
<hr >

<h3>ファイル内容(確認用)</h3>
<div>
  <img *ngIf="isImage" [src]="srcImage" />
  <pre *ngIf="isText" style="border:1px solid #333;padding:5px;margin:0;" >{{srcText}}</pre>
  <object *ngIf="isPdf" [data]="srcPdf" type="application/pdf"></object>
</div>

<br />

<h3>ファイル内容(Base64)</h3>
<div style="border:1px solid #333;padding:5px;word-wrap:break-word;word-break:break-all;">{{base64Text}}</div>

Component

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

@Component({
  selector: 'app-select-file',
  templateUrl: './select-file.component.html',
  styleUrls: ['./select-file.component.css']
})

export class SelectFileComponent implements OnInit {

  // ファイルの内容
  base64Text = ''; 

  // 選択されたファイルの種類(デバッグ用) 
  isImage = false;
  isText = false;
  isPdf = false;

  // ファイルの内容(デバッグ用) 
  srcImage = ''; 
  srcText = ''; 
  srcPdf: any = ''; 

  constructor(private sanitizer: DomSanitizer) {
  }

  /** 
   * 初期処理. 
   */  
  ngOnInit() {
  }

  /** 
   * ファイル選択時. 
   * (ElementRef を使用してもFile要素にアクセスは可能だが、
   *   ファイル選択時にイベント参照してデータ取得しておく方が手間は少なそう) 
   *  ※Base64エンコードデータへの変換中は Loading? 中に しておく等の工夫は必要かも。
   */  
  onFileSelect($event) {

    this.base64Text = ''; 
    this.srcImage = ''; 
    this.srcText = ''; 
    this.srcPdf = ''; 

    this.isImage = false;
    this.isText = false;
    this.isPdf = false;

    if ($event.target.files && $event.target.files.length > 0) {

      console.log($event.target.files[0]);

      // コンポーネント参照をthis以外で出来るようにしておく
      const pageObj = this;

      const file = $event.target.files[0];
      const fr = new FileReader();
      fr.onload = function(evt: any) {
        const base64Url  = evt.target.result;
        pageObj.base64Text = base64Url.replace(/^.+,/, '');
        if (base64Url.match(/^data:text\/.+/)) {
          // const plainText = atob(pageObj.base64Text);
          const plainText = pageObj.b64DecodeUnicode(pageObj.base64Text);
          pageObj.srcText = plainText;
          pageObj.isText = true;
          console.log('--- text ---');
          console.log(plainText);
        } else if (base64Url.match(/^data:image\/.+/)) {
          console.log('--- image ---');
          pageObj.srcImage = base64Url;
          pageObj.isImage = true;
        } else if (base64Url.match(/^data:application\/pdf/)) {
          pageObj.srcPdf = pageObj.sanitizer.bypassSecurityTrustResourceUrl(base64Url);
          pageObj.isPdf = true;
        }
      };
      fr.readAsDataURL(file);

    } else {
      console.log('not selected!');
    }
  }

  /**
   * Base64デコード
   * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22
   */
  b64DecodeUnicode(str) {
    // return atob(str);
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
  }

}

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2018-02-04 (日) 18:27:58 (2271d)