Home > OS >  How to send multiple files from Angular as FormData to Spring Boot as MultipartFile[]?
How to send multiple files from Angular as FormData to Spring Boot as MultipartFile[]?

Time:05-12

My code below is for a single file upload, but I am trying to send multiple files from Angular to Spring Boot all at once. Sending multiple formdata to an ArrayList in Spring Boot results in null, and I can't @RequestParam a single formdata in Spring Boot, since the amount of files sent from Angular is dynamic (defined by the user). Could anyone please help?

Spring Boot controller:

@PostMapping("/jobAdApplication")
public void jobAdApplication (@RequestParam("files") MultipartFile[] files, 
   @RequestParam("candidateName") String candidateName) {
       (...)
}

Angular component:

selectedFiles!: FileList;
file!: file;

(...)

if (this.selectedFiles) {
   let file: File | null = null;
   const formData: FormData = new FormData();

   for (let i = 0; i < this.selectedFiles.length; i  ) {
      file = this.selectedFiles.item(i);
      if (file) {
         formData.append(`file${i}`, file);
      }
   }

   formData.append('candidateName', this.applyFormGroup.get('name')?.value);

   this.fileService.uploadFile(formData).subscribe({
      next: response => {
         alert('Files sent successfully')
         this.applyFormGroup.reset();
      },
      error: err => {
         alert(`Error: ${err.message}`);
      }
   });

   this.selectedFiles = undefined;
}

Angular service:

uploadFile(jobAdApplication: FormData): Observable<any> {
   return this._http.post<any>(`${this.jobCandidateUrl}/jobAdApplication`, jobAdApplication);
}

CodePudding user response:

Doesn't selectedFiles!: FileList have to be an iterable? Like an array? Then the for (of) loop should be also changed to access file at index [i]. If it's an object, like a map you could use for (in) loop and get items using Object.entries.

Could you console log jobAdApplication before you POST it? I'm just curious what the data structure looks like.

If that is all okay then go over how you append the files.

Controller is expecting array of MultipartFile on param files.

@RequestParam("files") MultipartFile[] files

But here you append them to file with changing index.

 formData.append(`file${i}`, file);

Instead keep them named files so controller can access the right thing.

 formData.append('files', file);
  • Related