Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring rest return multipart/form-data with application/json content-type

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

like image 432
krku Avatar asked Jan 03 '23 10:01

krku


1 Answers

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--
like image 74
krku Avatar answered Jan 06 '23 02:01

krku