网站搜索

angular - 如何使用 ng2-file-upload 重置并允许上传文件


我正在使用 ng2-file-upload 来上传文件。它对我来说工作正常。我需要处理服务器端的错误并重置文件上传器。我该如何实现这个功能?以下是我正在使用的代码

HTML

        <div class="progress progressbar" style="height:10px;">
          <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
        </div>
        <button type="button" class="btn btn-warning btn-s button_gray" (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
        <span class="glyphicon glyphicon-ban-circle"></span> Cancel
      </button>
        <button type="button" class="btn btn-danger btn-s button_gray" (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
        <span class="glyphicon glyphicon-trash"></span> Remove
      </button>
        <button type="button" class="btn btn-primary btn-s" (click)="uploader.authToken=authToken ;uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
        <span class="glyphicon glyphicon-upload"></span> Upload
      </button>

Typescript

    ngOnInit() {
        this.uploader.onAfterAddingFile = (file) => {
          file.withCredentials = false;
          if (this.target) this.target.value = '';
        };
        this.uploader.onErrorItem = (item, response, status, headers) => this.onErrorItem(item, response, status, headers);
        this.uploader.onSuccessItem = (item, response, status, headers) => this.onSuccessItem(item, response, status, headers);
      }

  let data = JSON.parse(response); //success server response
    console.log(data)
    this.showSnackBar('Successfully Uploaded file.');
    this.router.navigate(['/result'])
  }

  onErrorItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
    let error;
    if (response != undefined && response.length > 0)
      JSON.parse(response); //error server response
    else
      error = response;

    console.log(error)
    this.showSnackBar('Error on Upload the file.');
  }

现在,如果出现任何故障,我就无法再次上传文件。

答案#1

我认为你解决了问题,但我仍然想为社区分享完整的解决方案

1- 将此添加到组件中

import { ViewChild, ElementRef } from "@angular/core";

2- 将此声明添加到组件中

@ViewChild("dummyID", { static: false }) 
myInputVariable: ElementRef; 

3- 在 HTML 文件中,为特定元素指定一个 ID(我使用了 #dummyID)

<input #dummyID type="file" ng2FileSelect [uploader]="uploader" />

4- 然后,当你能够在组件中访问到你想要的元素时,最佳实践是在 ng2-file-upload 的 onWhenAddingFileFailed 方法中使用它

this.uploader.onWhenAddingFileFailed = item => {
//some code
//some code

 this.myInputVariable.nativeElement.value = "";
};

答案#2

只需重置/清空队列。

this.uploader.queue = [];

相关文章