我正在基于Spring 3.2开发一个RESTful服务。我遇到了一个问题,处理混合的multipart HTTP请求的控制器,其中第一部分是XML或JSON格式的数据,第二部分是图像文件。
我使用@RequestPart注释来接收请求。
@RequestMapping(value = "/User/Image", method = RequestMethod.POST, consumes = {"multipart/mixed"},produces="applcation/json")
public
ResponseEntity<List<Map<String, String>>> createUser(
@RequestPart("file") MultipartFile file, @RequestPart(required=false) User user) {
System.out.println("file" + file);
System.out.println("user " + user);
System.out.println("received file with original filename: "
+ file.getOriginalFilename());
// List<MultipartFile> files = uploadForm.getFiles();
List<Map<String, String>> response = new ArrayList<Map<String, String>>();
Map<String, String> responseMap = new HashMap<String, String>();
List<String> fileNames = new ArrayList<String>();
if (null != file) {
// for (MultipartFile multipartFile : files) {
String fileName = file.getOriginalFilename();
fileNames.add(fileName);
try {
file.transferTo(new File("C:/" + file.getOriginalFilename()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
responseMap.put("displayText", file.getOriginalFilename());
responseMap.put("fileSize", "" + file.getSize());
response.add(responseMap);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Accept", "application/json");
return new ResponseEntity<List<Map<String, String>>>(response,
httpHeaders, HttpStatus.OK);
}
User.java会像这样 -
@XmlRootElement(name = "User")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int userId;
private String name;
private String email;
private String company;
private String gender;
//getter setter of the data members
}
根据我的理解,使用@RequestPart注释,我期望XML多部分部分将根据其Content-Type进行评估,并最终取消编组为我的User类(我正在使用Jaxb2,配置了适当的marshaller / unmarhaller在应用程序上下文中,并且当我将XML数据作为正文传递并使用@RequestBody注释时,该过程对于所有其他控制器方法都有效)。但实际发生的是,尽管文件被正确地找到并解析为MultipartFile,但“user”部分从未被看到,并且请求始终失败,不匹配控制器方法签名。
我使用几种客户端类型重现了这个问题,并且我有信心multipart请求格式没问题。
请帮助我解决这个问题,也许有一些解决方法可接收混合/多部分请求。
谢谢和问候,
Raghvendra
consumes = {"multipart/form-data"}
? - Stijn Geukens