Angular 文件上傳

下面做的是Angular  實現文件上傳的一個小功能。

首先在你所需要用到的ts中導入:

import { DomSanitizer } from '@angular/platform-browser';

在constructor()中依賴注入private sanitizer: DomSanitizer:

 constructor( private sanitizer: DomSanitizer) {

  }

HTML:

<div class="formCenter" style="width: 650px; height: 350px">
    <img [src]="imgUrl" alt="圖片" style="width: 600px; height: 300px" title="圖片" class="form-control">
    <input type="file" accept="image/.jpg, image/.png" (change)="fileChange($event)" class="fileInput">
  </div>

ts:

imgUrl;
// 聲明<img [src]="{{imgUrl}}"/>

  fileChange(i) {
    const file  = i.target.files[0];
    const imgUrl = window.URL.createObjectURL(file);
    const sanitizerUrl = this.sanitizer.bypassSecurityTrustUrl(imgUrl);
    this.imgUrl = sanitizerUrl;
    console.log(this.imgUrl);
  }

結果是這個樣子:

期待更好的方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章