Saroj Maharjan
Saroj Maharjan

Reputation: 97

Angular2 call http post method using for loop

I am trying to upload multiple files with title for each file but while passing request to server I am trying to pass each file and its title one by one. I have a array named bindArray that has data like

bindArray = [{file: File(), title: 'abc'}, {file:File(), title: 'bcd'}]

Now I am using loop in array to send each file and title to server. when I take [0] of bindArray it send the request to server and it executes successfully but in next request i.e of [1] it is sending data of [0] too and request fails. I checked this in my chrome console network tab and found it while requesting for [1] previous file and data is also being sent and causing error. I have searched about my issue but none of the solution available is working as expected. I dont know why this is happening.

here is my complete code

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);
 }

Upvotes: 1

Views: 109

Answers (1)

Bhanu Tej P
Bhanu Tej P

Reputation: 230

You have to create a new instance of form Data on each loop so that the formData will have only one record.

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);

 // add these lines
 const uploadData = this.formData;
 this.formData = new FormData();
 // add these lines

 this.doctorService.uploadDocuments(uploadData, docType)
   .subscribe(response => {
     console.log(response, "response")
   }, err => {
    console.log(err, 'err');
   });
} 

Upvotes: 1

Related Questions