29

我为 spring 3 rest 多部分文件上传做了一个 POC。它工作正常。但是当我尝试与我的应用程序集成时,我遇到了问题。

它抛出以下异常:

org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;
nested exception is org.apache.commons.fileupload.FileUploadException:
the request was rejected because no multipart boundary was found**"

如果我在代码的任何部分有错误,请告诉我。

豆子:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 <property name="order" value="1" />
 <property name="mediaTypes">
 <map>
   <entry key="json" value="application/json" />
   <entry key="xml" value="application/xml" />
   <entry key="file" value="multipart/mixed" />
 </map>
</property>
</bean>
<!-- multipart resolver -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- one of the properties available; the maximum file size in bytes -->
  <property name="maxUploadSize" value="50000000" />
 </bean>

控制器:

@Controller
public class MultipleFilesRecieve {
    @RequestMapping ( value = "/saveMultiple", method = RequestMethod.POST )
        public String save( FileUploadForm uploadForm ) {
        List<MultipartFile> files = uploadForm.getFiles( );
        List<String> fileNames = new ArrayList<String>( );
        if ( null != files && files.size( ) > 0 ) {
            for ( MultipartFile multipartFile : files ) {
                String fileName = multipartFile.getOriginalFilename( );
                fileNames.add( fileName );
            }
        }
        return "multifileSuccess";
    }
}
4

4 回答 4

34

问题不在您的代码中,而是在您的请求中。您在多部分请求中缺少边界。正如规范中所说:

多部分实体的 Content-Type 字段需要一个参数“boundary”,用于指定封装边界。封装边界定义为完全由两个连字符(“-”,十进制代码 45)组成的行,后跟来自 Content-Type 头字段的边界参数值。

这个这个帖子也应该有帮助。

于 2013-09-04T18:40:41.553 回答
5

@sermolaev 的回答是正确的。

我想分享我与这个问题相关的经验。我在Postman中遇到过这个问题,但我很长时间都无法理解它的根本原因。我的请求模板似乎是正确的,因为 Postman 包含boundary在其中...

最终我发现,当您Content-Type=multipart/form自己指定标题时,它会覆盖 Postman 自动添加的标题。这会导致与您相同的错误。我的解决方案就像删除Content-Type标题一样简单。

于 2017-08-04T18:46:12.263 回答
0

您是否使用任何安全过滤器?我的问题是通过删除安全过滤器链解决的。由此:

this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(this.springSecurityFilterChain).build();

对此:

this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

我打开了一个问题,我解释了详细信息: https ://jira.spring.io/browse/SPR-12114

于 2014-08-21T22:01:05.120 回答
0

不要Content-Type在请求中提供标头。它会起作用的。

于 2019-01-15T08:16:11.077 回答