Created
April 29, 2020 23:51
-
-
Save NazemMahmud/5e516b5cae24a803023afb4a4523bcee to your computer and use it in GitHub Desktop.
Angular-material & Laravel: multiple & single file upload : Angular part (3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component, OnInit} from '@angular/core'; | |
import {FormBuilder, FormGroup, Validators} from '@angular/forms'; | |
import {Subject} from 'rxjs'; | |
import {takeUntil} from 'rxjs/operators'; | |
// your extra code if you needed… | |
export class FileUploadComponent implements OnInit, OnDestroy { | |
formGroup: FormGroup; | |
disabled = true; | |
removable = true; | |
formData = new FormData(); | |
myFiles: any [] = []; | |
// ... | |
constructor( private _fb: FormBuilder ) {} | |
ngOnInit(): void { | |
this.initiateForm(); | |
} | |
initiateForm(): void { | |
this.formGroup = this._fb.group({ | |
first_name: ['', Validators.required] | |
}); | |
} | |
filePushByChecking(files): void { | |
let tempFiles = []; | |
for (let i = 0; i < files.length; i++) { | |
tempFiles.push(files[i]); | |
} | |
/* checking for duplicate files, duplicate file should not push again */ | |
for (let i = 0; i < tempFiles.length; i++) { | |
for (let j = 0; j < this.myFiles.length; j++){ | |
if (this.myFiles[j].name == tempFiles[i].name) { | |
tempFiles.splice(i, 1); | |
} | |
} | |
} | |
for (let i = 0; i < tempFiles.length; i++) { | |
this.myFiles.push(files[i]); | |
} | |
} | |
/* pushing files into an array */ | |
uploadFile(files: FileList): void { | |
/* if already files are pushed before( i.e. first time), then need to update the array */ | |
if (this.myFiles.length > 0) { | |
this.filePushByChecking(files); | |
} | |
else { | |
/* for first time pushing new files into the array */ | |
for (let i = 0; i < files.length; i++) { | |
this.myFiles.push(files[i]); | |
} | |
} | |
} | |
remove(file): void { | |
for (let i = 0; i < this.myFiles.length; i++) { | |
if (this.myFiles[i].name == file.name) { | |
this.myFiles.splice(i, 1); // remove the item | |
break; | |
} | |
} | |
} | |
onSubmit(): void { | |
if (this.formGroup.valid) { | |
this.formData.append('name', this.formGroup.get('first_name').value); | |
for (let i = 0; i < this.myFiles.length; i++) { | |
this.formData.append('files[]', this.myFiles[i]); | |
} | |
this.save(this.formData); | |
} else { | |
this.invalidFormData('Data may not be valid or empty'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment