gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:53:58 24 4
gpt4 key购买 nike

我正在使用 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- 将此添加到组件中

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- 然后,您可以在组件中到达您想要的元素,最佳做法是在 中使用它onWhenAddingFileFailed ng2文件上传方法
this.uploader.onWhenAddingFileFailed = item => {
//some code
//some code

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

关于angular - 如何使用 ng2-file-upload 重置并允许上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51026300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com