java - 如何接受Spring boot + MVC中的任何路径

标签 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

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

我假设框架正在尝试推断有关 pdf 的信息,但不知道如何处理它。我认为这只是一个配置问题...我怎样才能仅针对该端点停止该行为?

尝试失败:

  • 按照某人的建议尝试关闭 WebMvcConfigurerAdapter 的后缀模式匹配

    configurer.setUseSuffixPatternMatch(false);

最佳答案

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);
      }
    }

关于java - 如何接受Spring boot + MVC中的任何路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834996/

相关文章:

java - FileWriter 未写入其所有内容 - 如何绕过最大值?

java - 单次后台线程,避免连接?

java - 停止 Spring MVC 注解处理

java - 使用@Valid 会抛出异常并且在基本的 Spring 3.0 MVC 程序中不起作用

spring-mvc - Spring 安全 webSecurity.ignoring()

java - Spring 4/Spring 社交 - PageNotFound - 在 DispatcherServlet 中未找到带有 URI 的 HTTP 请求的映射

java - 在 Felix 框架中存储对象

java - 如何从 java.util.HashMap 转换为 android.content.ContentValues?

java - 如何限制上传到 Spring MVC3 Controller 的文件类型

java - Autowiring Spring 父类(super class)