赞
踩
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(“出错”):
}
});
接收前端的信息,组装调用第三方接口,传输同样的信息:
@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);
}
@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";
}
@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"));
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。