2

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

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Joosep, I changed the selectedFiles!: any[], which seems to work just fine, and formData.append('files', file) works perfectly right. Sound obvious, but not logically to me in terms of two instances having the same name/identifier ('files'). It seemed as one would replace the other. But it seems obvious in terms of backend property matching and it works. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.