Spring REST上传文件时,MultipartFile文件始终为空。

5
@RequestMapping(value = "{fileName:.+}", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<ResponseEnvelope<String>> uploadFile(
         @RequestParam("ownerId") Long ownerId, 
         @PathVariable("fileName") String fileName,
         @RequestBody MultipartFile file)
         throws Exception {
    ResponseEnvelope<String> env;
    if(null == certFileContent) {
        env = new ResponseEnvelope<String>("fail");
        return new ResponseEntity<ResponseEnvelope<String>>(env, HttpStatus.OK);
    }
    service.uploadCertificate(ownerId, fileName, certFileContent.getBytes());
    env = new ResponseEnvelope<String>("success");
    return new ResponseEntity<ResponseEnvelope<String>>(env, HttpStatus.OK);
}

我经常遇到文件值为空的问题,但是我已经配置了multipart支持,请看下面的内容:

你是否也在HTML的<form />标签上添加了enctype="multipart/form-data"(参见http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2)? - sp00m
我使用Rest客户端进行测试,同时选择了“multipart/form-data”作为内容类型,谢谢。 - Berry2081898
2个回答

3
文件应该绑定到RequestParam而不是RequestBody,如下所示:
public ResponseEntity<ResponseEnvelope<String>> uploadFile(
         @RequestParam("ownerId") Long ownerId, 
         @PathVariable("fileName") String fileName,
         @RequestParam(value = "file") MultipartFile file)

这将对应以下HTML表单:
```html

这是一个段落。

```
<form method="post" action="some action" enctype="multipart/form-data">
    <input type="file" name="file" size="35"/>
</form>

然后在您的调度程序配置中指定CommonsMultiPartResolver


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
</bean>

感谢您的回复,我已经尝试使用@RequestParam,但是我遇到了另一个问题, "{"error":{"status":400,"message":"在执行此请求期间发生未知错误。","errorParams":{"exceptionMessage":"所需的MultiPart参数'file'不存在"}}}",我也在我的配置中指定了commonsMultiPartResolver,非常感谢。 - Berry2081898
问题已解决,问题在于我需要指定参数名称...当我进行post操作时,谢谢。 - Berry2081898
@Berry2081898,我现在遇到了这个问题,你说的指定POST参数名是什么意思?我正在使用AJAX进行POST请求。非常感谢您的帮助,谢谢!这是我的stackoverflow问题链接:http://stackoverflow.com/questions/27772803/uploading-files-using-the-spring-framework-and-jquery-upload-file-plugin-issue - charliebrownie
@Berry2081898 或许你也可以发布自己的答案,这样其他人也能看到它! - charliebrownie

3
这是我的经验之谈,
我之前定义的input字段如下,
<input type="file" />

在使用上述代码时,我得到了一个空文件,但是当我添加了name="file"后,一切都正常了!

<input type="file" name="file" />

希望这能帮到你!

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