Spring REST返回multipart/form-data与application/json内容类型

5

我正在构建一个 API,其响应为multipart/form-data格式,其中包含application/json内容,但遇到了问题。

例如:

http://localhost:8080/getData 

应该返回

--HaRZrgSMRFElYDqkcBMfTMp3BUMHKQAtP
Content-Disposition: form-data; name="response"
Content-Type: application/json

[{"name":"xyz"}]
--HaRZrgSMRFElYDqkcBMfTMp3BUMHKQAtP--

当前的代码片段是

@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;   
}

我收到的响应是{}一个空的JSON对象。 可以有人告诉我哪里出错了吗?

1个回答

12

我已经找到了解决方案,发帖分享以便对其他人有所帮助。

@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);
}

响应

--57XYHIgdIhRSOYu6TZA-ybSppMuAtcN3
Content-Disposition: form-data; name="response"
Content-Type: application/json
Content-Length: 1186

[{"sample": "sample"}]
--57XYHIgdIhRSOYu6TZA-ybSppMuAtcN3--

你知道如何使用这样的数据吗? - Vadim Kirilchuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接