加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用角度反应形式上传多个文件

发布时间:2020-12-17 18:07:12 所属栏目:安全 来源:网络整理
导读:我正在尝试在Angular 6中构建一个表单,它提供了一个文件选择框,允许用户选择多个文件(Stackblitz: https://stackblitz.com/edit/angular-yjummp). 模板看起来像: form [formGroup]="form" input id="files" formControlName="files" type="file" accept="i
我正在尝试在Angular 6中构建一个表单,它提供了一个文件选择框,允许用户选择多个文件(Stackblitz: https://stackblitz.com/edit/angular-yjummp).

模板看起来像:

<form [formGroup]="form">
    <input id="files" formControlName="files" type="file" accept="image/*,video/*" multiple (change)="onFilesChanged($event)"/>
</form>

我在TypeScript中构建表单,如下所示:

public form = new FormGroup({
    files: new FormControl('')
  });

  public onFilesChanged(event: any): void {
    console.log(event.target.files);
    console.log(this.form.value);
  }

现在,在onFilesChanged处理程序中,通过访问event.target.files(显然)可以从事件中正确检索所选文件,但是打印表单值只会打印一个文件.我一直在尝试使用FormArray的多种方法,但到目前为止还没有运气.

有任何想法吗?非常感谢!

解决方法

以下是我如何通过角度反应形式实现多个照片上传输入文件的示例.

public demoForm: FormGroup;

constructor(private formBuilder: FormBuilder) { 
    this.demoForm = this.formBuilder.group({
       text_input: ['',Validators.required],photos: this.formBuilder.array([])
    });
}

// We will create multiple form controls inside defined form controls photos.
createItem(data): FormGroup {
    return this.formBuilder.group(data);
}

//Help to get all photos controls as form array.
get photos(): FormArray {
    return this.roomForm.get('photos') as FormArray;
};

detectFiles(event) {
    let files = event.target.files;
    if (files) {
        for (let file of files) {
            let reader = new FileReader();
            reader.onload = (e: any) => {
                this.photos.push(this.createItem({
                    file,url: e.target.result  //Base64 string for preview image
                }));
            }
            reader.readAsDataURL(file);
        }
    }
}

在组件html中

<input type="file" class="custom-file-input form-control" id="files" multiple (change)="detectFiles($event)" accept="image/x-png,image/jpeg">

<div class="images-preview mt-2" *ngIf="photos.length">
    <div formArrayName="photos" *ngFor="let photo of photos.controls; let i = index;">
        <div [formGroupName]="i">
            <img [src]="photo.controls.url.value" class="card-img-top" alt="Image Preview">
        </div>
    </div>
</div>

如果您不想显示预览,可以避免使用html.提交表格后,您将获得如下的价值.

{
    text_input: "",photos: [
       {
           file: <File Object>,url: <Base64 String here>
       },{
           file: <File Object>,....
    ] 
}

我希望它能帮助你和其他人民.谢谢.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读