如何从Angular Reactive Form接收文件上传? [英] How to receive file upload from Angular Reactive Form?

查看:40
本文介绍了如何从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、docs 或其他格式)

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 发布图像,我只需将这个属性放在我的 FormControl 中就获得了文件对象 writeFile="真".这可以将 FileList 对象写入 FormControl 中作为值.要实现这一点,您需要安装@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆