angular - Angular 4:文件上传:无法在“HTMLInputElement”上设置“value”属性
问题描述
**TS FILE**
export class CreateqpComponent implements OnInit {
createQPForm:FormGroup;
constructor(private fb:FormBuilder,private http:Http) { }
ngOnInit() {
this.createQPForm=this.fb.group({
qpName:['',[Validators.required]],
file:['',[Validators.required]]
});
}
onFileChange(event) {
if (event.target.files.length > 0 ){
const file1=event.target.files[0];
this.createQPForm.get('file').setValue(file1);
}
}
<form [formGroup]="createQPForm" (ngSubmit)="createQP()">
<div class="form-group">
<label for="qpName" class="col-sm-3 col-form-label">File Name</label>
<input type="text" class="form-control" formControlName="qpName" id="qpName" placeholder="SeaQueenBoat">
</div>
<div class="form-group">
<label for="file" class="col-sm-3 col-form-label">Select File:</label>
<input type="file" accept=".zip" class="form-control" formControlName="file" (change)="onFileChange($event)"/>
</div>
</form>
当我选择一个文件时,它给了我一个错误:
ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
我是 Angular 的新手,无法找到其他解决方案。
谁能解释我如何解决这个错误?
解决方案
您可以将文件保存在 ts 文件中的变量中,并在提交表单时使用它:-
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http'
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html'
})
export class FileUpload implements OnInit {
createQPForm: FormGroup;
fileHolder: File | null;
constructor(
private _FormBuilder: FormBuilder,
private _HttpClient: HttpClient
) {
this.fileHolder = null;
}
ngOnInit() {
this.createQPForm = this._FormBuilder.group({
qpName: ['', [Validators.required]],
file: ['', [Validators.required]]
});
}
onFileChange(event) {
if (event.target.files && event.target.files.length) {
this.fileHolder = event.target.files[0];
}
}
createQP() {
if (this.createQPForm.valid && this.fileHolder && this.fileHolder.name) {
const formData: FormData = new FormData();
formData.append('qpName', this.createQPForm.value.qpName);
formData.append('file', this.fileHolder, this.fileHolder.name);
// use the formDat here
}
}
}
请参阅此处的工作堆栈闪电战。
推荐阅读
- c# - Visual Studio 2019 OpenXML 波兰字母
- python - 从菜单获取信息的进展
- r - 从 R 中的列表中检索每个矩阵的信息
- javascript - 从帧重定向中获取 url
- oracle - 从 NetSuite 到 Oracle EPM 的 GET 请求,但面临“需要授权 - 您无权访问请求的资源
- javascript - 如何实现异步/等待
- amazon-web-services - AWS - Fargate - 将 EFS 添加到容器 - 从 AWS 控制台
- typescript - VSCode - 禁用“这可能会转换为异步函数”工具提示消息
- ios - 从试飞安装时,Expo iOS 应用程序崩溃
- jenkins - 种子作业创建MavenJob失败但不报错