Angular 2从输入类型=文件上传文件 [英] Angular 2 File upload from input type=file

查看:102
本文介绍了Angular 2从输入类型=文件上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用诊断我可以看到双向绑定的其他<$ c

$ p $ < form><
{{diagnostic}}
< div class =form-group>
< label for =fileupload>上传< / label>
< input type =fileclass =form-control[(ngModel)] =model.fileupload>
< / div>
< / form>

在我的打印文件中,我有诊断行可用:

  get diagnostic(){return JSON.stringify(this.model); } 

难道是不是JSON的问题?值是 null



我无法真正验证输入的值;不知何故,尽管旁边的选择文件...更新文本,我看不出在DOM的差异。

解决方案

认为它不被支持。如果你看看 DefaultValueAccessor 指令(参见https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23)。你会看到用来更新绑定元素的值是 $ event.target.value



由于可以到达 $ event.srcElement.files ,因此不适用于类型 file

有关更多详细信息,请参阅此plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info

  @Component({ 
selector:'my-app',
template:`
< div>
< input type =file(change)=onChange($ event) />
< / div>
`,
providers:[UploadService]
})
export class AppComponent {
onChange(event){
var files = event.srcElement.files;
console.log(files);
}
}


Using angular 2 beta, and I cannot seem to get input of type file to work.

Using diagnostic I can see two-way binding for other types such as text.

<form>
    {{diagnostic}}
    <div class="form-group">
        <label for="fileupload">Upload</label>
        <input type="file" class="form-control" [(ngModel)]="model.fileupload">
    </div>
</form>

In my typescript file I have the diagnostic line available:

get diagnostic() { return JSON.stringify(this.model); }

Could it be that it is the issue of not being JSON? The value is null.

I cannot really verify the value of the input; somehow even though the text next to "Choose file ..." updates, I cannot see differences in the DOM.

解决方案

I think that it's not supported. If you have a look at this DefaultValueAccessor directive (see https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23). You will see that the value used to update the bound element is $event.target.value.

This doesn't apply in the case of inputs with type file since the file object can be reached $event.srcElement.files instead.

For more details, you can have a look at this plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
  }
}

这篇关于Angular 2从输入类型=文件上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆