如何通过HTML的输入标记获取文件的引用?(Angular 2)

flp*_*lpn 2 html web firebase angular

我想在Firebase上传图片.但要做到这一点,我必须先得到文件.如何通过HTML获取计算机的图像?我正在尝试这样做,但我不知道这是什么回报.帮帮我们......

<input type="file" name="image" [(ngModel)]="myImage">
Run Code Online (Sandbox Code Playgroud)

Mid*_*vin 12

您可以使用DOM元素引用ElementRef,然后提取从元素引用上载的文件的数据.使用#variableName引用文件输入.

<input #fileInput (change)="fileUpload()" type="file" name="pic" accept="image/*">
Run Code Online (Sandbox Code Playgroud)

在组件类中,使用引用文件输入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]; 

  }
}
Run Code Online (Sandbox Code Playgroud)

我在这里创建了一个样本plunker .