angular - 使用角度形式和 ngModel 将文件分配给变量
问题描述
我想使用一个表单将一个文件分配给一个变量,以便我可以将文件发布到我的后端服务器。
我的表格如下所示:
<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”变量的值。
我在我的 TS 文件中将变量简单地定义为:
uploadedFile: any
对于文件以外的任何类型的输入,此方法都有效,因为变量会更新以显示已输入的内容。但是,对于我浏览并选择文件时的文件,变量保持为空。当我单击提交时,我通过将变量“uploadedFile”输出到控制台来确认这一点。但是即使在我选择了一个文件之后,该变量也会返回为“未定义”。必须做什么才能将文件分配给这个 uploadFile 变量?
解决方案
你应该做这个:
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
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。
这里还有另一个例子: https ://medium.com/@amcdnl/file-uploads-with-angular-reactive-forms-960fd0b34cb5
推荐阅读
- android - 如何获取 Android Slices 的彩色文本?
- c - C - 到 uint64_t 的时间
- c# - 是否可以防止在 C# WinForms 对话框中创建业务对象?
- react-native - 使用 Mirage.js [模拟 API 调用] React-Native 进行排毒
- makefile - 从 GNUmake 中的变量内容中过滤掉不需要的东西
- django - 如何正确使用 MongoDB 客户端连接
- google-maps - 如何在颤动中分配纬度和经度值?
- javascript - 如何为 ColumnListItems 设置组标题
- sql - 选择相同计数的位置
- c# - 统一测试中SetUp后当前上下文中不存在该名称