'How do I upload multiple files in array in Angulars reactive forms, from an API and send the data as a number to the array
***ERROR IMAGE: *** https://ibb.co/JKd0hV3
Who can help me solve this problem, I get a 490error whenever I run this code. Am I missing something or need to refacture something. I need to upload multiple files to a array in reactive forms like bellow:
component.ts
this.myForm = this.fb.group({
name: [''],
multipleFileArray: this.fb.array([]),
})
This is my api function in the service component, where I call the request
mainService.service.ts
upload(file: File): Observable<HttpEvent<any>> {
const formData: FormData = new FormData();
formData.append('file', file);
const req = new HttpRequest('POST', '/document/upload', formData, {
responseType: 'json',
});
return this.http.request(req);
}
Here is my function for upload and detecting chages, maybe i need to refactor them who knows...
component.ts
myFiles: FileList;
progressInfos = [];
onChange(event: any) {
// this.selectedFiles.push(event.target.files);
this.progressInfos = [];
this.selectedFiles = event.target.files;
}
uploadFiles(): void {
if (this.selectedFiles) {
for (let i = 0; i < this.selectedFiles.length; i++) {
this.upload(i, this.selectedFiles[i]);
}
}
}
upload(idx: number, file: File): void {
this.progressInfos[idx] = { value: 0, fileName: file.name };
if (file) {
this.mainService.upload(file).subscribe({
next: (event: any) => {
if (event.type === HttpEventType.UploadProgress) {
this.progressInfos[idx].value = Math.round((100 * event.loaded) / event.total);
} else if (event instanceof HttpResponse) {
this.showMessage('Uploaded the file successfully: ' + file.name);
}
},
error: (err: any) => {
this.progressInfos[idx].value = 0;
this.showMessage('Could not upload the file: ' + file.name);
},
});
}
}
And here is my HTML
component.html
<input type="file" class="hide" multiple (change)="onChange($event)" #fileUpload placeholder="Upload file" />
<a (click)="fileUpload.click()">Upload document</a>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
