3

I was working on a file upload widget for managing images.

I wish that image paths can be received via @PathVariable in Spring MVC, such as http://localhost:8080/show/img/20181106/sample.jpg instead of http://localhost:8080/show?imagePath=/img/20181106/sample.jpg.

But / will be resolved Spring MVC, and it will always return 404 when accessing.

Is there any good way around this?

Jimmy Wang
  • 33
  • 5

2 Answers2

4

You can use like below.

@RequestMapping(value = "/show/{path:.+}", method = RequestMethod.GET)
public File getImage(@PathVariable String path) {
        // logic goes here
}

Here .+ is a regexp match, it will not truncate .jpg in your path.

Alien
  • 15,141
  • 6
  • 37
  • 57
1

Sorry to say that, but I think the answer of @Alien does not the answer the question : it only handle the case of a dot . in the @PathVariable but not the case of slashes /.

I had the problem once and here is how I solved it, it's not very elegant but stil ok I think :

private AntPathMatcher antPathMatcher = new AntPathMatcher();

@GetMapping("/show/**")
public ... image(HttpServletRequest request) {
    String uri = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    String path = antPathMatcher.extractPathWithinPattern(pattern, uri);

    ...
}
Romain Warnan
  • 1,022
  • 1
  • 7
  • 13