简体   繁体   中英

spring rest webservices 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

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--

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM