带有ngForm模块的Angular4表单输入文件

时间:2017-08-13 03:50:42

标签: angular

文件不发送。

点击事件中未附加该文件。

通过控制台,json显示为空。

<form #form="ngForm" enctype="multipart/form-data" novalidate>

<input type="file" id="file" name="file1" class="form-control" ngModel>

<input type="file" id="file" name="file2" class="form-control" ngModel>

                <button class="btn btn-primary" (click)="envirArquivos(form.value)">Enviar</button>

          </form>

文件ts

import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'mw-compare-nfe',
  templateUrl: './compare-nfe.component.html'
})
export class CompareNFEComponent implements OnInit {

    constructor() { }

  ngOnInit() {
  }

  envirArquivos(form) {
    console.log(form);
  }

}

{&#34;文件1&#34;:&#34;&#34;&#34;文件2&#34;:&#34;&#34;} 空

1 个答案:

答案 0 :(得分:2)

您无法使用input type = 'file'访问ngForm,因为文件类型的值未绑定到$event.target.value,而是event.target.files

所以你可以做的一件事是:

  • 更新您的HTML

    <input type="file" id="file" name="file1" class="form-control" ngModel (change)="getFiles($event)">

  • 添加更改事件

  • 并在JS文件中监听更改事件。

    getFiles(event) {
        console.log(event.target.files);
    }
    
  • 现在,您可以将这些值存储在变量中,并使用表单提交。