我正在尝试在Angular 8中上传文件,但出现以下错误且无法弄清
ERROR DOMException: "An attempt was made to use an object that is not, or is no longer, usable"
选择文件时出现上述错误。下面是我的方法
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但此处元素已经加载的情况下出现的,而不是为什么出现此错误?
答案 0 :(得分:1)
那个错误很奇怪。 当我测试您的代码时,收到以下错误:
错误:无法在'HTMLInputElement'上设置'value'属性:此输入元素接受文件名,只能以编程方式将其设置为空字符串。
只需在您的HTML模板中删除formControlName='photo'
即可使用。
编辑
要显示错误,必须使用与常规输入不同的方法。文件输入没有ng-touched,ng-untouched或ng-dirty类,因此您无法执行以下操作:
<p *ngIf="photo.invalid && (photo.dirty || photo.touched)"> Show an error </p>
我想您想在用户点击“提交”按钮时显示输入文件的错误。 如果是这样,您可以执行以下操作:
// 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->允许您定位单个控件;
updateValueAndValidity()->通知Angular值已更改,它必须检查该值是否有效。
我创建了这个StackBlitz来检查代码(对样式感到抱歉)。如果您的项目中需要一个图像预览,我会提供一个图像预览。