2017-04-07 88 views

回答

3

可以使用ElementRef引用DOM元素,然後從中提取元素參考上傳的文件的數據。使用#variableName來引用文件輸入。

<input #fileInput (change)="fileUpload()" type="file" name="pic" accept="image/*"> 

在您的組件類中,使用ViewChild引用文件輸入。

import {Component, ElementRef, Renderer2, ViewChild} from '@angular/core' 
@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>{{name}}</h2> 
     <input #fileInput (change)="fileUpload()" type="file" name="pic" accept="image/*"> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    @ViewChild('fileInput') el:ElementRef; 
    constructor(private rd: Renderer2) { 
    this.name = `Angular : File Upload` 
    } 

    fileUpload() { 
    console.log(this.el); 
    // Access the uploaded file through the ElementRef 
    this.uploadedFile = this.el.nativeElement.files[0]; 

    } 
} 

我已經創建了一個示例plunker here

+0

Awsome dude!非常感謝! – flpn

相關問題