I've encountered an issue while attempting to upload multiple files with individual titles. The problem arises when sending requests to the server, as I'm trying to pass each file and its corresponding title one by one. I have an array called bindArray which stores data in the following format:
bindArray = [{file: File(), title: 'abc'}, {file:File(), title: 'bcd'}]
Currently, I am using a loop through the array to send each file and title to the server. However, after successfully sending the request for index [0] of bindArray, the subsequent request for index [1] also includes the data from index [0], leading to a failure. Upon inspecting the network tab in Chrome console, I observed that while requesting index [1], the previous file and data are unintentionally being sent along, causing errors. Despite researching potential solutions for this issue, none seem to work as desired. I'm perplexed as to why this behavior is occurring.
Below is the complete code snippet:
upload.html
<input id="cin" name="file" type="file" (change)="fileChangeEvent($event)"
multiple placeholder="Upload a file..."/>
<form #submitCertificate="ngForm">
<div class="input" *ngFor="let a of titleArray">
<input type="text" [(ngModel)]="a.title" name="title" *ngIf="showInput" (blur)="blurMethod()" placeholder="title"> <br>
</div>
</form>
<button type="submit" (click)="upload('certificate')">upload</button>
upload.component.ts
files;
formData;
titleArray = [];
showTitle: boolean = false;
showInput: boolean = false;
blurMethod() {
this.title = this.titleArray;
}
fileChangeEvent(evt) {
this.showInput = true;
this.files = evt.target.files;
for (let i = 0; i < this.files.length; i++) {
this.addTitle();
}
}
upload(docType) {
if (this.files.length > 0) {
let file;
let title;
const bindArray = [];
this.formData = new FormData();
for (let i = 0; i < this.files.length; i++) {
for (let j = 0; j <= i; j++) {
file = this.files[i];
title = this.titleArray[j].title;
if (i === j) {
this.imageNameArray.push(file.name);
bindArray.push({
file: file,
title: title
});
}
}
}
for (let k = 0; k < bindArray.length; k++) {
let formFile = {name: ''};
let formFileName = '';
let formTitle = '';
formFile = bindArray[k].file;
formFileName = formFile.name;
formTitle = bindArray[k].title;
this.formData.append('file', formFile, formFileName);
this.formData.append('title', formTitle);
this.doctorService.uploadDocuments(this.formData, docType)
.subscribe(response => {
console.log(response, "response")
}, err => {
console.log(err, 'err');
});
}
}
doctorService.ts
uploadDocuments(formData, docType) {
const headers = new Headers();
headers.append('type', docType);
return this.apiHelperService.post('https://someurl', formData, {headers: headers})
.map(response => {
return response.json();
})
.catch(this.handleError);
}