@RequestPart在使用Spring MVC 3.2.4进行多部分请求时始终为空。

4
我正在开发一个基于Spring 3.2.4的小型RESTful服务,并遵循这篇文章编写自定义函数以发送多部分请求。
首先,在控制器中,我编写了一个示例函数进行测试。
@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对象也为空。

我该如何解决?

请帮助我解决这个问题。


你看过这个吗?http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-multipart-forms-non-browsers - geoand
是的,我有。我改变了遵循此文档的代码,但我仍然得到“用户名:null”。你有什么想法吗? - Tan Viet
1个回答

3

回答有点晚,但仍然有用。这是我使用@RequestPart附加有效载荷和文件的方法:

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody String create(@RequestPart Blah blah, 
        @RequestPart(value = "uploadfile", required=false) MultipartFile) {...}

以下curl命令可以验证上述内容:
curl -i -X POST -H "Content-Type: multipart/mixed" \
-F "blah={\"name\":\"mypayloadname\"};type=application/json" \
-F "uploadfile=@somevalid.zip" http://localhost:8080/url/path

请确保对负载内容进行转义,一些有效的.zip文件(第二个-F是可选的,因为已将其设置为false)应该与curl在同一目录中执行或替换为文件的有效路径。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接