I'm new to angular , and I'm learning how to upload multiple files to my server. So what I've been able to do is that I can upload files, display a spinner then display that files under the upload button .
component.html :
<div fxFlex="50" class="mb-24" *ngIf="show">
<button mat-raised-button color="primary" (click)="hiddenfileinput.click()" fxFlex="50">
<mat-icon>cloud</mat-icon>
load documents
</button>
<input type="file" id="fileUpload" name="fileUpload" multiple (change)="onUpload($event)" #hiddenfileinput style="display:none;"/>
</div>
<div *ngIf="!isLoading ; else loadBlock">
<div *ngFor="let file of viewFiles">
<span><mat-icon>attachment</mat-icon>{{file}}</span>
</div>
</div>
<ng-template #loadBlock>
<mat-spinner [diameter]="20"></mat-spinner>
</ng-template>
Component.ts UploadFunction :
viewFiles : string[]= [];
isLoading = false;
files: FormData = new FormData();
onUpload(event)
{
this.isLoading = true;
const fdata = event.target.files;
for (let i = 0; i < fdata.length; i++)
{
this.files.append('file[]', fdata[i], fdata[i].name);
}
for (var pair of this.files.values())
{
this.viewFiles.push(pair.name);
}
setTimeout(() => {
this.isLoading = false
},2500)
}
So here's the problem what if the user clicks the upload button , uploads 1 file and then clicks again on the button and uploads the same file and 3 others files, then I ll have a duplicated file on the list , how can I check if the file already exists ? or avoid duplicated files ?
Thanks !
EDIT
Found a working solution :
this.isLoading = true;
const fdata = event.target.files;
for (let i = 0; i < fdata.length; i++)
{
for (var pair of this.files.values())
{
if(pair.name == fdata[i].name)
{
this.fileExists = true;
}
}
if (!this.fileExists) {
this.files.append('file[]', fdata[i], fdata[i].name);
this.viewFiles.push(fdata[i].name);
}