在客户我有:
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
var data = {f_name: 'test1', s_name: 'test2'};
var fd = new FormData();
fd.append('data', angular.toJson(data));
fd.append("file", file);
$http({
method: 'POST',
url: 'EmployeeService/employee/upload',
headers: {'Content-Type': undefined},
data: fd,
transformRequest: angular.identity
})
.success(function(data, status) {
alert("success");
});
}
在服务器上(Spring):
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String postFile(@RequestParam(value="file", required=false) MultipartFile file,
@RequestParam(value="data") Object data) throws Exception {
System.out.println("data = " + data);
return "OK!";
}
但是data
是字符串:&#34; {&#34; f_name&#34;:&#34; test1&#34;,&#34; s_name&#34;:&#34; test2&# 34;}&#34 ;. A有DTO级:
public class EmployeeDTO(){
private String f_name;
private String s_name;
//setters and getters
}
在服务器上我想得到:
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String postFile(@RequestParam(value="file", required=false) MultipartFile file,
@RequestParam(value="data") EmployeeDTO employeeDTO) throws Exception {
//etc.
}
如何从客户端(文件和数据)以及服务器获取文件和EmployeeDTO对象发送数据?
答案 0 :(得分:0)
虽然您可以使用注释@RequestBody
从json字符串中获取Object。
例如:
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@RequestBody EmployeeDTO employeeDTO){
//TODO do something;
return "success";
}
或者您可以接收字符串,然后使用ObjectMapper将字符串转换为对象
例如:
EmployeeDTO employeeDTO = new ObjectMapper().readValue("here is json string", EmployeeDTO.class);
答案 1 :(得分:0)
您可以注册使用Json Converter<String, EmployeeDTO>
的{{1}},您可以根据需要编写控制器方法(我假设您使用Jackson2)
如果你只需要这种方法,那么明确地做它可能更简单:
ObjectMapper
或者,您可以将对象直接放在FormData(angularJS侧)中,并使用@Autowired
private MappingJackson2HttpMessageConverter jsonConverter;
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String postFile(@RequestParam(value="file", required=false) MultipartFile file,
@RequestParam(value="data") String data) throws Exception {
EmployeeDTO employeeDTO = jsonConverter.getObjectMapper().readValue(data,
EmployeeDTO.class);
return "OK!";
}
弹簧侧获取它:
@ModelAttribute
和
var fd = new FormData();
fd.append("file", file);
fd.append("f_name", 'test1');
fd.append("s_name", 'test2'};