Angular上传图片后如何重置文件输入表单?

How to reset file input form after uploading the image in Angular?

我们有 2 个与 select 编辑文件和上传文件相关的问题。第一个问题是,当您上传图像时,文件名仍保留在输入中。这是代码。

OnFileSelected(event) {
    const file: File = event[0];

    this.ReadAsBase64(file)
      .then(result => {
        this.selectedFile = result;
      })
      .catch (err => this.error = err);

  }

  Upload() {
    if (this.selectedFile) {
      this.usersService.AddImage(this.selectedFile).subscribe(
        data => {
          this.socket.emit('refresh', {});
          console.log(data);
          this.SettingsForm.reset()
        },
        err => err
      );
    }
  }
  ReadAsBase64(file): Promise<any> {
    const reader = new FileReader();
    const fileValue = new Promise((resolve, reject) => {
      reader.addEventListener('load', () => {
        const result = reader.result;
        if (!result) reject('Cannot read variable');
        if (this.images.length>=4) reject('You can have only 4 images');
        if (result.length * 2  > 2**21) reject('File exceeds the maximum size'); // Note: 2*2**20 = 2**21 
        resolve(reader.result);
      });

      reader.addEventListener('error', event => {
        reject(event);
      });

      reader.readAsDataURL(file);
    });

    return fileValue;
  }

HTML

 <div>
                <div class="form-group">
                    <label for="exampleFormControlFile1">Example file input</label>
                    <input #myInput ng2FileSelect [uploader]="uploader" (onFileSelected)="OnFileSelected($event)" type="file"
                        class="form-control-file" id="exampleFormControlFile1" />
                </div>
                <p *ngIf="error"> {{error}}</p>
                <button (click)="Upload()" type="submit" class=" btn btn-default submit-btn btn-upload ">
                    <i class="material-icons">attachment</i>
                    Upload Image</button>
            </div>

上传图片后如何重置表单? 另外,如何让错误消息显示 3 秒?如果你 select 错误的文件错误一直存在,即使在添加有效文件之后也是如此。我们考虑过添加

setTimeout(() => {

        }, 3000); // just example
      },

但不确定在哪里添加?我该如何解决这 2 个问题?

你可以这样做 在你的 component.ts

import { ViewChild } from '@angular/core';

然后定义一个变量来保存它:

@ViewChild('myInput')
myInputVariable: ElementRef;

然后在你的函数中

Upload() {
    if (this.selectedFile) {
      this.usersService.AddImage(this.selectedFile).subscribe(
        data => {
          this.socket.emit('refresh', {});
          console.log(data);
          this.myInputVariable.nativeElement.value = "";
        },
        err => {
            console.log(err);
        }
      );
    }
  }

要删除错误: OnFileSelected(事件){ const 文件:File = event[0];

this.ReadAsBase64(file)
  .then(result => {
    this.selectedFile = result;
  })
  .catch (err => {this.error = err; setTimeout(()=> {this.error = ''},2000}));

}