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

时间:2018-06-25 14:49:37

标签: angular typescript npm 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>

打字稿

    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 个答案:

答案 0 :(得分:0)

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

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 = "";
};