Angular 8反应式表单文件上载错误 [英] Error in Angular 8 reactive form file upload

查看:68
本文介绍了Angular 8反应式表单文件上载错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 8中上传文件,但出现以下错误且无法弄清

I am trying to upload file in Angular 8 but getting below error and not able to figure it out

ERROR DOMException: "An attempt was made to use an object that is not, or is no longer, usable"

选择文件时出现

以上错误.下面是我的方法

above error comes when I select a file. Below is my approach

Component.ts

Component.ts

import { Component, OnInit } from '@angular/core';
import {FormArray,FormBuilder,FormGroup,FormControl, Validators, NgForm} from "@angular/forms";
import { ApiService } from '../apis/commonapis';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  userForm : FormGroup;
  constructor(private fb : FormBuilder,private service : ApiService) { }

  ngOnInit() {
    this.newForm(); 
  }
  newForm = function(){
    this.userForm = this.fb.group({
      email : ['',Validators.compose([Validators.required])],
      photo : ['',Validators.compose([Validators.required])]
    })
  }
  PostData(form: NgForm) {
    //console.log(form);
    var formData = new FormData();
    formData.append('photo', this.userForm.get('photo').value);
    console.log(formData);
    /*this.service.PostApi("http://localhost:1900/addUser",formData).subscribe(res=>{
                console.log(res);
                location.reload();
            });
     */
  }

  onFileSelect(event) { // here is some error
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.userForm.get('photo').setValue(file);
    }
  }
}

模板文件

<form [formGroup]="userForm" (ngSubmit)="PostData(userForm)" enctype="multipart/form-data"> 
        <div class="form-group row">
                <label for="email" class="col-sm-2 col-form-label">Email</label>
                <div class="col-sm-9">
                        <input type="text"  formControlName='email' class="form-control" required>
                </div>                                                                                                    
        </div>

        <div class="form-group row">
                <label for="photo" class="col-sm-2 col-form-label">Photo</label>
                <div class="col-sm-9">
                        <input type="file"  formControlName='photo' class="form-control" required  (change)="onFileSelect($event)">
                </div>                                                                                                    
        </div>

        <div class="form-group row">

                <div class="col-sm-10">
                        <input type="submit"  value='submit' class="form-control">
                </div>                                                                                                    
        </div>

</form>

我已经搜索了上述错误,并且说此错误是在未加载DOM但此处元素已经加载的情况下出现的,而不是为什么出现此错误的原因?

I have searched for above error and it says this error comes when DOM is not loaded but here element is already loaded than why this error?

推荐答案

该错误很奇怪. 当我测试您的代码时,收到以下错误:

That error is strange. When I tested your code I received the following error:

错误:无法在'HTMLInputElement'上设置'value'属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串.

Error: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

只需在您的HTML模板中删除formControlName='photo'即可.

Just delete formControlName='photo' in your HTML template and should work.

编辑

要显示错误,必须使用不同于常规输入的方法.文件输入没有ng-touched,ng-untouched或ng-dirty类,因此您不能执行以下操作:

For displaying errors, you have to use a different approach than for regular inputs. File input doesn't have ng-touched, ng-untouched or ng-dirty classes, so you can't do something like:

<p *ngIf="photo.invalid && (photo.dirty || photo.touched)"> Show an error </p>

我想您想在用户点击提交"按钮时显示输入文件的错误. 如果是这样,您可以执行以下操作:

I suppose you want to display the error for the file input when the user hits the submit button. If so, you can do something like:

// add a property to your class
isPhotoError = false;

PostData(form: NgForm) {
    if (this.userForm.get('photo').invalid) {
      this.isPhotoError = true;
    }
    //do something
 }

photoErrorHandler() {
    if (this.userForm.get('photo').hasError('required')) {
      return 'Photo required';
    }
  }

<p *ngIf="isPhotoError"> {{ photoErrorHandler() }} </p>

考虑将您的onFileSelect(event)替换为:

onFileSelect(event: Event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.userForm.patchValue({ photo: file });
    this.userForm.get('photo').updateValueAndValidity();
  }

patchValue->允许您定位单个控件;

patchValue -> allows you to target a single control;

updateValueAndValidity()->通知Angular值已更改,它必须检查该值是否有效.

updateValueAndValidity() -> informs Angular that the value has been changed and it has to check if the value is valid or not.

我已经创建了这个 StackBlitz 来检查代码(对样式感到抱歉).如果您的项目中需要一个图像预览,那么我会提供一个图像预览.

I have created this StackBlitz to check the code (sorry about the styles). I have included an image preview if you need one in your project.

这篇关于Angular 8反应式表单文件上载错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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