【发布时间】:2022-02-10 20:13:35
【问题描述】:
我正在尝试在 Angular 8 中上传文件,但出现以下错误并且无法弄清楚
ERROR DOMException: "An attempt was made to use an object that is not, or is no longer, usable"
当我选择一个文件时出现上述错误。以下是我的方法
组件.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 时出现的,但是这里的元素已经加载了,而不是为什么这个错误?
【问题讨论】:
-
对您的代码进行了公认的肤浅阅读,一切似乎都很好。我建议您创建一个 StackBlitz 来显示错误,以便 SO 的成员可以帮助您进一步挖掘。
-
@dmcgrandle stackblitz.com/edit/angular-vmfh1t
-
@user1234 参考这个答案stackoverflow.com/questions/55291422/…
-
@UshmiDave 非常感谢您关注我的问题 :)
标签: angular