如何从Angular Reactive Form接收文件上传? [英] How to receive file upload from Angular Reactive Form?
问题描述
我有模块以Angular 7反应形式上载文件(我需要反应形式,因为我需要一起上载文件和其他一些信息)
I have module to upload file in Angular 7 Reactive Forms ( I need reactive form because I need to upload files and some other information together)
我关注这篇文章: https://medium.com/@amcdnl/file -uploads-with-angular-reactive-forms-960fd0b34cb5
代码如下: https://pastebin.com/qsbPiJEX
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();
};
}
}
据我所知,我将收到json数据中的文本。
但我不知道如何将其作为文件接收或将json数据转换为文件。该文件可以是图像,pdf或其他文档(excel,文档或其他格式)
as far I know, I will receive the file as text inside the json data. But I have no idea how to receive this as a file or convert the json data to file. The file could be images, pdf or other docs (excel, docs, or other formats)
我正在使用Dotnet Core 2.2和Angular 7
任何想法接收文件?
I am using Dotnet Core 2.2 and Angular 7 Any idea how to receive the file ?
推荐答案
我有一个要通过formData发布图像的表单,我在其中有fileobject我的FormControl只需将此属性放入 writeFile = true
。这可以将FormControl中的FileList对象作为值写入。为此,您需要安装 @ rxweb / reactive-form-validators软件包并注册 RxReactiveFormsModule模块。就是这样。
I'm having a form in which i want to post image through formData, i got fileobject in my FormControl just by putting this attribute writeFile="true"
. This can write the FileList object in your FormControl as value. To Achieve this you need to install the package of '@rxweb/reactive-form-validators' and register the 'RxReactiveFormsModule' module. That's it.
这是我的html代码:
here is my html code :
<form [formGroup]="userFormGroup">
<label>Profile Photo</label>
<input type="file" [writeFile]="true" formControlName="profilePhoto" multiple />
<button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
</form>
请参考以下示例: Stackblitz
这篇关于如何从Angular Reactive Form接收文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!