4

我正在使用 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>

打字稿

    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.');
  }

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

4

1 回答 1

2

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

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 = "";
};
于 2019-10-17T03:23:53.780 回答