I am having problem building a api whose response is multipart/form-data with application/json content
example:
http://localhost:8080/getData
should return
--HaRZrgSMRFElYDqkcBMfTMp3BUMHKQAtP
Content-Disposition: form-data; name="response"
Content-Type: application/json
[{"name":"xyz"}]
--HaRZrgSMRFElYDqkcBMfTMp3BUMHKQAtP--
the current code snippet is
@RequestMapping(value="/getData", method=RequestMethod.GET,
produces=MediaType.MULTIPART_FORM_DATA_VALUE)
public MultipartFile getMultipartAsFileAsObject() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("sample.json").getFile());
String readFile = readFile("sample.json");
DiskFileItem fileItem = new DiskFileItem("file", "application/json", false, "response", (int) file.length() , file);
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}
and the response i am getting is {} an empty json object. can someone let me know where i am going wrong
I have figured out the solution, posting it so it could be helpful for others
@RequestMapping(method = { RequestMethod.GET }, value = "/getData", produces =
MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MultiValueMap<String, Object>> getData() {
s= "[{\"sample\": \"sample\"}]";
JsonArray ja = (new JsonParser()).parse(s).getAsJsonArray();
MultiValueMap<String, Object> mpr = new LinkedMultiValueMap<String, Object>();
HttpHeaders xHeader = new HttpHeaders();
xHeader.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> xPart = new HttpEntity<String>(ja.toString(), xHeader);
mpr.add("response", xPart);
return new ResponseEntity<MultiValueMap<String, Object>>(mpr,
HttpStatus.OK);
}
Response
--57XYHIgdIhRSOYu6TZA-ybSppMuAtcN3
Content-Disposition: form-data; name="response"
Content-Type: application/json
Content-Length: 1186
[{"sample": "sample"}]
--57XYHIgdIhRSOYu6TZA-ybSppMuAtcN3--
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With