个人小结---RestTemplate传递String与MultipartFile参数Post

1.前端样例

var file_data = $("#file").prop("files")[0]; //单个文件
var fd = new FormData();   
var jsonObj = '{'
    +'"name1" : "'+$("#name").val()+'",'
    +'"alarmList" : '+JSON.stringify(alarmDetailData)+''
   +'}';

//传递字符串与文件
fd.append("file", file_data);
fd.append("jsonStr", jsonObj);
$.ajax({
    url:"../callsaveFileAndStr1.json",
    type: "POST",
    contentType: false,
    processData: false,
    data: fd,
    error: function () {
        alert(出错):

    }
});

2.同应用Controller接收

接收前端的信息,组装调用第三方接口,传输同样的信息:

@PostMapping(value = "callsaveFileAndStr1.json")
@ResponseBody
public void saveQuestionSheetInfo(
        @RequestParam(value = "file",required = false) MultipartFile file, String jsonStr) throws IOException {

  ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
    @Override
    public String getFilename() {
      return file.getOriginalFilename();
    }

    @Override
    public long contentLength() {
      return file.getSize();
    }
  };
  String url = "http://localhost:8088/saveFileAndStr2";
  MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
  multipartRequest.add("file", fileAsResource);
  multipartRequest.add("jsonStr", jsonStr);

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);

  HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity (multipartRequest,headers);
  //发起调用
  ResponseEntity<String> response = restTemplate
          .postForEntity(url, requestEntity, String.class);

}

3.调用第三方

3.1 接收层

@RequestMapping(value = "/saveFileAndStr2", method = RequestMethod.POST)
@ResponseBody
public String saveFileAndStr2(String jsonStr,
    @RequestParam(value = "file", required = false) MultipartFile file) {
  System.out.println(jsonStr);
  InfoVO VO= JSON.parseObject(jsonStr, InfoVO.class);
  String filePath = "C:\\Users\\admin\\Desktop\\ddddd.txt" ;
  File desFile = new File(filePath);
  try {
    file.transferTo(desFile);
  } catch (IOException e) {
    e.printStackTrace();
  }
  return "success";
}

3.2 测试用例

@Test public void saveFileAndStr2() throws Exception {
  //注意:MockIFile的属性名为“file”
  MockMultipartFile jsonFile = new MockMultipartFile("file", "", "application/json", "{\"json\": \"someValue\"}".getBytes());
  String jsonStr = "{\"name\":\"zzz\"}";
  mockMvc.perform(MockMvcRequestBuilders.multipart("/saveFileAndStr2")
      .file(jsonFile)
      .param("jsonStr", jsonStr))
      .andExpect(status().is(200))
      .andExpect(content().string("success"));
}

 

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值