如何接受Spring boot + MVC

时间:2017-08-23 08:52:37

标签: java spring spring-mvc spring-boot

我想使用Spring Boot + MVC定义一个端点,它接受包含URL中所需目标路径的多部分文件上载。

示例:

形成网址http://localhost:8080/upload/file/path/to/somefile.pdf我希望稍后提取/path/to/somefile.pdf以便使用它。

到目前为止,这是我得到的:

@RequestMapping(method= RequestMethod.PUT, value="/file/**", consumes = "multipart/form-data")
@ResponseBody
public UploadResult uploadFile(final HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
  //parse from path is ok.
}

它捕获任何路径(包含斜杠)文件后缀。所以这有效:

http://localhost:8080/upload/file/path/to/somefile

但这不是

http://localhost:8080/upload/file/path/to/somefile.pdf

它会回答由406引起的org.springframework.web.HttpMediaTypeNotAcceptableException

我认为框架试图推断有关pdf的内容,并且不知道要处理它。我认为这只是一个配置问题......我怎样才能停止那个端点的行为?

尝试失败:

  • 尝试关闭来自WebMvcConfigurerAdapter的后缀模式匹配,如有人建议

    configurer.setUseSuffixPatternMatch(false);

1 个答案:

答案 0 :(得分:0)

HttpMediaTypeNotAcceptableException or 406 means we have problems with Content Negotiation. By default spring will first check with the path extension. 
In your case, your endpoint have suffix with .pdf, so it is expecting as application.pdf or pdf is required but your end point defined something else. So it gives 406 error. you can check more details here
<https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc>

To resolve the issue you can easily change this configuration using ContentNegotiationConfigurer accessed by extending WebMvcConfigurerAdapter. 



 @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {

      @Override
      public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
      }
    }