i'm looking for a solution where i can send at the same time a csv file and other data (angular) to the Spring boot backend. in my case i cant use a FormData because the data i need to send is not only strings (data are heterogenous) so My DTO in the front looks like something below :
export class example {
id: number;
addresses?:string[];
status :string;
createdBy?: string;
createdDate?: Date;
collections : int[]
addressesDocument: File; // <------- file i need to send to the backend
}
in the backend i've created a similar DTO containing a MultipartFile as type for the file but i got always an exception
@PostMapping("/examples")
public void createExample(@Valid @RequestBody ExampleDTO example) throws URISyntaxException, FileNotFoundException {
System.out.println(exampleDTO.getfile());
exampleService.create(example);
}
what is the best solution to send a file along with other divers data in the same API ???
CodePudding user response:
You cannot send the file as part of the json-object, as indicated in your sample-code. Though it's possible to use content-type multipart/form-data
and then separately append the file on one hand and the rest of the data on the other hand, to FormData
.
The Post-request in the Angular-frontend would then look something like this:
saveFileAndData(file: File, exampleDataObject: Example) {
const formData = new FormData();
formData.append('file', file);
formData.append('data', JSON.stringify(exampleDataObject));
const headers = new HttpHeaders();
headers.set('Content-Type', 'multipart/form-data');
this.http.post('/examples', formData, { headers: headers })
.subscribe();
}