web-services – 当与@RequestParam MultipartFile一起使用时,Spring MVC @RequestBody给我一个空字符串

我有这个Web服务代码的问题

@Controller
@RequestMapping("/u_tutorial")
public class UploadTutorial
{
    @RequestMapping(value = "tutorial1", method = RequestMethod.POST, headers = "Accept=application/json")
    @ResponseStatus(value = HttpStatus.OK)
    public void upload(@RequestBody String body, @RequestParam List<MultipartFile> file, Principal principal,
        HttpServletRequest request)
    {
        System.out.println("body: " + body); // always empty

        for (MultipartFile mf : file)
        {
            System.out.println("file: " + mf.getOriginalFilename());
        }
    }
}

情况是当我想在请求体中上传带有一些数据的文件时,我的body变量总是给我一个空字符串.

但是当我尝试仅使用“@RequestBody String body”或“@RequestParam List file”时,它就像一个魅力.

我做了一些搜索,发现这是因为InputStream问题.一些建议的解决方案已经讨论过,但与我的问题并不完全相关(或者可能是肯定但我不明白).

有谁能给我一个解决方案?谢谢.

PS 1.这是我的图书馆版本

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.core.version>3.1.4.RELEASE</spring.core.version>
    <spring.security.version>3.1.3.RELEASE</spring.security.version>
    <spring.data.mongodb.version>1.1.0.RELEASE</spring.data.mongodb.version>
    <cglib.version>2.2</cglib.version>
    <aspectj.version>1.6.10</aspectj.version>
    <mongodb.driver.version>2.10.1</mongodb.driver.version>
    <!-- Logging -->
    <slf4j.version>1.6.1</slf4j.version>
    <log4j.version>1.2.14</log4j.version>
    <javax.jstl-taglibs.version>1.1.2</javax.jstl-taglibs.version>
    <jackson.version>1.9.3</jackson.version>
    <!-- Testing -->
    <mockito.version>1.8.5</mockito.version>
    <junit.version>4.8.2</junit.version>
    <!-- Plugins -->
    <maven.copy.plugin.version>0.2.3</maven.copy.plugin.version>
    <maven.compiler.plugin.version>2.3.2</maven.compiler.plugin.version>
    <maven.apt.plugin.version>1.0</maven.apt.plugin.version>
    <!-- Utilities -->
    <apache.common.io.version>2.4</apache.common.io.version>
    <apache.common.fileupload.version>1.2.2</apache.common.fileupload.version>
    <jodatime.version>2.1</jodatime.version>
</properties>

PS 2.对不起我的英语.

最佳答案
您可以将“body”字符串设置为表单上的隐藏字段,并将其作为另一个@RequestParam发布,而不是将其作为单独的@RequestBody参数.所以你的表单看起来像这样:

<form id="myForm" method="post" enctype="multipart/form-data">
    <input type="hidden" name="body" value="bodyValue"/>
    <input type="file" name="file"/>
    ...

控制器看起来像这样:

public void upload(@RequestParam String body, @RequestParam List<MultipartFile> file, Principal principal, HttpServletRequest request)
....

转载注明原文:web-services – 当与@RequestParam MultipartFile一起使用时,Spring MVC @RequestBody给我一个空字符串 - 代码日志