I have to pass the object in "multipart/form-data" request so that it can be received in downstream application (Java Spring) as List i.e custom class object. Metadata object contains only key and value
In Angular
interface Metadata{
key:string;
value:string;
}
In Angular I am using FormData to create the multipart request as given below.
metadatas = new Array<Metadata>();
// few values added in metadatas array.
fileToUpload: File ; // contains file information
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
formData.append('metadata',JSON.stringify(this.metadatas))
As FormData append method definition says the "value: string | Blob" so I need to convert my metadatas object to string using JSON.stringify(). But when I do so in Spring application (downstream), I can receive the object in String e.g
@PostMapping(path = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> fileUpload(
@RequestParam(name = "metadata", required = false) String metadata,
@RequestParam(name = "file", required = false) MultipartFile file) {
System.out.println(metadata);
System.out.println(file);
return new ResponseEntity<>("example", HttpStatus.OK);
}
Above code is working and able to get the metadata and file data, but as my API says it should be received in Java Object. So my spring method definition it should be List. Again here the metdata is the object contain key and value.
In Java
public class Metadata {
private String key;
private String value;
// getter and setters
}
In below code the metadata should be capture in List
@PostMapping(path = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> fileUpload(
@RequestParam(name = "metadata", required = false) List<Metadata> metadata,
@RequestParam(name = "file", required = false) MultipartFile file) {
System.out.println(metadata);
System.out.println(file);
return new ResponseEntity<>("example", HttpStatus.OK);
}
I tried varies things with @RequestPart and @RequestParam, but nothing is working out. As per my understanding, I think that as I am converting the metadata in string while sending from angular hence I am able to received it in String object.
But in FormData I don't have any option to append the object directly as it allows string or Blob. Is there any other way to send the multipart object without converting to string in angular? Or even if we send the object using FormData how we can received the object in Java Class i.e. List in Spring Boot Application ?
Please help me for getting the solution with the detail explanation as I am new to this.