使用斜角的反应形式上载多个文件

时间:2019-08-05 14:33:09

标签: angular

我想上传多个文件,并想显示使用反应形式上传的图像文件的预览

我尝试使用formArray,但未显示图像。

ngOnInit() {
    this.initForm();

  }
  initForm() {
    this.multiForm = this.fb.group({
      albumName: ['', Validators.required],
      multiImages: this.fb.array([this.createImage()])
    })
  }
  createImage() {
    const newImage = new FormControl("", Validators.required);
    (<FormArray>this.multiForm.get('multiImages')).push(newImage)
  }

  get multiImages() : FormArray {
    return this.multiForm.get('multiImages') as FormArray;
  }

onFileUpload(event:any) {
    this.urls = [];
    let selectedFiles =  event.target.files;
    console.log(selectedFiles);
    if(selectedFiles) {
      for(let file of selectedFiles) {
        let reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        }
        reader.readAsDataURL(file);
      }
    }
  }

HTML文件

<div class="uk-margin">
            <div class="js-upload uk-placeholder uk-text-center uk-width-1-2 uk-margin-left">
                <span uk-icon="icon: cloud-upload"></span>
                <span class="uk-text-middle">Attach binaries by dropping them here or</span>
                <div uk-form-custom>
                    <input type="file" (change)="onFileUpload($event)" name="multiImages" multiple>
                    <span class="uk-link"> selecting one</span>
                </div>
            </div>
        </div>
        <div class="uk-margin">
             <div class="uk-flex">
            <button class="uk-button uk-margin-large-left" (click)="onSubmit()">Submit</button>
            </div>
        </div>
        <div *ngIf="multiImages.length">
            <div formArrayName="multiImages" *ngFor="let image of multiImages.controls; let i = index">
            <div [formGroupName] = "i">
            <img class="uk-flex uk-margin-large-left" [src]="image.controls.url.value" width="180" />
        </div>
        </div>
        </div>

应该显示多张图片的预览。

1 个答案:

答案 0 :(得分:0)

我看不到您实际上在将任何值推入FormArray的任何地方,因此您需要这样做。您可以在将值推入urls数组的同时执行此操作。在这里,我使用您拥有的createImage()函数:

reader.onload = (e: any) => {
  this.urls.push(e.target.result);
  this.createImage(e.target.result);
}

createImage()

createImage(img) {
  const newImage = new FormControl(img, Validators.required);
  (<FormArray>this.multiForm.get('multiImages')).push(newImage)
}

建立表单时,您叫createImage,将其删除。添加图像后,在模板中按原样迭代表单数组,并使用image.value显示图像:

<div  *ngFor="let image of multiImages.controls; let i = index">
  <div [formGroupName]="i">
    <img [src]="image.value" width="180" />
  </div>
</div>

这里是 DEMO