在最终版本中,这实际上很容易做到。花了我一些时间来解决这个问题,因为我遇到的有关它的大多数信息都已过时。如果其他人为此感到困扰,请在此处发布我的解决方案。
import { Component, ElementRef, Input, ViewChild } from '@angular/core';import { Http } from '@angular/http';@Component({ selector: 'file-upload', template: '<input type="file" [multiple]="multiple" #fileInput>'})export class FileUploadComponent { @Input() multiple: boolean = false; @ViewChild('fileInput') inputEl: ElementRef; constructor(private http: Http) {} upload() { let inputEl: HTMLInputElement = this.inputEl.nativeElement; let fileCount: number = inputEl.files.length; let formData = new FormData(); if (fileCount > 0) { // a file was selected for (let i = 0; i < fileCount; i++) { formData.append('file[]', inputEl.files.item(i)); } this.http .post('http://your.upload.url', formData) // do whatever you do... // subscribe to observable to listen for response } }}然后像这样使用它:
<file-upload #fu (change)="fu.upload()" [multiple]="true"></file-upload>
这就是全部。
或者,捕获事件对象并从srcElement获取文件。老实说,不确定是否有任何方法比其他方法更好!
请记住,FormData是IE10 +,因此,如果必须支持IE9,则需要使用polyfill。



