SPRING REST:请求被拒绝,因为没有找到多部分边界

时间:2013-07-04 05:42:29

标签: spring rest spring-mvc file-upload

我为春季3休息多部分文件上传做了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 个答案:

答案 0 :(得分:32)

问题不在您的代码中 - 它在您的请求中。您在多部分请求中缺少边界。正如它在specification中所说:

  

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

This this帖子也应该有所帮助。

答案 1 :(得分:3)

@sermolaev的答案是正确的。

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

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

答案 2 :(得分: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

答案 3 :(得分:0)

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

相关问题