我正在开发一个基于Spring 3.2.4的小型RESTful服务,并遵循这篇文章编写自定义函数以发送多部分请求。
首先,在控制器中,我编写了一个示例函数进行测试。
用户对象包含使用 Jackson JSON 获取和解析数据的用户信息。我还使用 cURL 发送请求并测试了命令。
这是 text.txt 文件。
应用程序返回“成功创建!”并记录了用户名。一切正常。
其次,我以为一切都很简单,但我错了。当我编写以下函数以使用用户和MultipartFile对象发送多部分请求时。
首先,在控制器中,我编写了一个示例函数进行测试。
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public @ResponseBody String createUser(@RequestBody User user)
{
if (user != null) {
log.debug("Username: " + user.getUsername());
}
return "Successfully created!";
}
用户对象包含使用 Jackson JSON 获取和解析数据的用户信息。我还使用 cURL 发送请求并测试了命令。
curl http://localhost:8080/user/createUser --data-binary @test.txt -X POST -i -H "Content-Type: application/json"
这是 text.txt 文件。
{
"id" : "123456",
"username" : "YOUR_USERNAME",
"password" : "YOUR_PASSWORD",
"email" : "YOUR_EMAIL"
}
应用程序返回“成功创建!”并记录了用户名。一切正常。
其次,我以为一切都很简单,但我错了。当我编写以下函数以使用用户和MultipartFile对象发送多部分请求时。
@RequestMapping(
value = "/createUser",
method = RequestMethod.POST,
consumes = {"multipart/mixed", "multipart/form-data"})
public @ResponseBody String createUser(
@RequestPart("user") @Valid User user,
@RequestPart("file") MultipartFile file) {
if (user != null) {
log.debug("Username: " + user.getUsername()); // The username is null
}
return "Successfully created!";
}
我继续使用cURL命令进行测试
curl http://localhost:8080/user/createUser --data-binary @test.txt -X POST -i -H "Content-Type: multipart/mixed; boundary=4ebf00fbcf09"
文本文件 text.txt 已更改。
--4ebf00fbcf09
Content-Disposition: form-data; name="user"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: 8bit
{
"id" : "123456",
"username" : "YOUR_USERNAME",
"password" : "YOUR_PASSWORD",
"email" : "YOUR_EMAIL"
}
--4ebf00fbcf09
Content-Disposition: form-data; name="file"; filename="no_thumb.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<... File Data ...>
--4ebf00fbcf09--
我面临的问题是@RequestPart始终为NULL。详情如下:
- 应用程序返回“创建成功!”
- 用户对象不为空,但服务器记录了“用户名:null”和MultipartFile对象也为空。
我该如何解决?
请帮助我解决这个问题。