使用角度形式和 ngModel 将文件分配给变量 [英] Assigning a file to a Variable using angular forms and ngModel

查看:22
本文介绍了使用角度形式和 ngModel 将文件分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用表单将文件分配给变量,以便我可以将文件发布到我的后端服务器.

I want to use a form to assign a file to a variable so that I can then post the file to my back end server.

我的表单如下所示:

<form (ngSubmit)='onSubmit()' #myform='ngform'>
<div class="fileup">
    <label for='file'> Upload </label>
    <input id='file' type='file' name='file' [(ngModel)] = 'uploadedFile' />
    <button type='submit' class='btn btn-basic'> Upload </button>
</form>


{{ uploadedFile ¦ json }}

最后一行仅用于开发目的,让我可以查看 'uploadedFile' 变量的值.

The final line is just for development purposes and allows me to see the value of the 'uploadedFile' variable.

我在我的 TS 文件中简单地将变量定义为:

My in my TS file i have defined the variable simply as:

uploadedFile: any

对于除文件以外的任何类型的输入,此方法都有效,因为变量会更新以显示已输入的内容.但是,当我浏览并选择文件时,对于该文件,该变量保持为空.我通过在单击提交时将变量uploadedFile"输出到控制台来确认这一点.但是即使在我选择了一个文件之后,该变量也会返回为未定义".必须做什么才能将文件分配给这个 uploadFile 变量?

For any type of input other than file this method works, in that, the Variable updates to show what has been entered. However for the file when I browse and select a file, the variable remains empty. I confirm this by outputting the variable 'uploadedFile' to the console when i click submit. But the variable is returned as 'undefined' even after I have selected a file. What has to be done to assign the file to this uploadedFile variable?

推荐答案

你应该这样做:

html:

<form (ngSubmit)='onSubmit()' #myform='ngform'>
<div class="fileup">
    <label for='file'> Upload </label>
    <input id='file' type="file" (change)="onFileChange($event)" />
    <button type='submit' [disabled]="formGroup.invalid || formGroup.prestine" class='btn btn-basic'> Upload </button>
</form>


{{ uploadedFile ¦ json }}

然后在你的 Component.ts 中

THen in your Component.ts

export class CustomComponent {

  formGroup = this.fb.group({
    file: [null, Validators.required]
  });

  constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) {}

  onFileChange(event) {
    const reader = new FileReader();

    if(event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);

      reader.onload = () => {
        this.formGroup.patchValue({
          file: reader.result
       });

        // need to run CD since file load runs outside of zone
        this.cd.markForCheck();
      };
    }
  } 
}

总结:每次上传新文件时,您都会更新 FormGroup.

In Conclusion: every time you upload a new file you will update the FormGroup.

这里还有一个例子:https://medium.com/@amcdnl/file-uploads-with-angular-reactive-forms-960fd0b34cb5

这篇关于使用角度形式和 ngModel 将文件分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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