Issue
I want to pass json and file together in the controller using curl. I have following method in controller.
@PostMapping(value = /api/campaign, headers = {"content-type=multipart/mixed","content-type=multipart/form-data"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public @Valid ResponseDTO campaignCreator (@Valid @RequestBody CampaignCreatorDTO campaignCreatorDTO, @RequestPart("file") MultipartFile adGraphic){
}
Below is the curl command
curl -i -X POST -H "Content-Type: multipart/mixed" -d "campaignCreatorDTO={\"edipi\":123456789,\"firstName\":\"John\",\"lastName\":\"Smith\",\"email\":\"[email protected]\"};type=application/json" -F "[email protected];type=image/png" http://localhost:8080/api/campaign
controller method is not getting called. when I put json in a file and use file in curl command in place of direct json it works. But I do not want to use file for json.
I tried to use @RequestPart for json object but same issue.
is there any way to pass multipart file inside json I mean CampaignCreatorDTO object?
Update:: Now I am able to pass RequestPart for both type but image size is coming 0 bytes. Though iamge is present in the filesystem.
Updated Code :: now using below code, and getting filesize as 0 bytes.
@PostMapping(value = /api/campaign, consumes = {"multipart/form-data","multipart/mixed"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public @Valid ResponseDTO campaignCreator (@Valid @RequestPart("json") CampaignCreatorDTO campaignCreatorDTO, @RequestPart("file") MultipartFile adGraphic) {
}
I tried solution given in this link but still same issue
Spring MVC Multipart Request with JSON
this is how client is paasing the data to server
let formData = new FormData()
const blob = new Blob([json], {
type: 'application/json'
});
formData.append("json", blob)
formData.append("file", values.adCreativeImageCover)
let authToken = sessionStorage.getItem("authToken")
fetch(/api/campaign, {
method: "POST",
headers: {
'Accept': 'application/json',
'X-Auth-Token': authToken,
},
mode: 'cors',
body: formData
})
Solution
I solved the issue by implementing multipartresolver in configuration.
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
Answered By - Anjali