There is a task to pass file path as @PathVariable
in Spring MVC to REST Service with GET
request.
We can easily do it with POST
sending String of file path in JSON.
How we can do with GET
request and @Controller
like this?
@RequestMapping(value = "/getFile", method = RequestMethod.GET)
public File getFile(@PathVariable String path) {
// do something
}
Request:
GET /file/getFile/"/Users/user/someSourceFolder/8.jpeg"
Content-Type: application/json
Ok.
you use to get pattern.
sending get pattern url.
Use @RequestParam.
@RequestMapping(value = "/getFile", method = RequestMethod.GET)
public File getFile(@RequestParam("path") String path) {
// do something
}
and if you use @PathVariable.
@RequestMapping(value = "/getFile/{path}", method = RequestMethod.POST)
public File getFile(@PathVariable String path) {
// do something
}
You should define your controller like this:
@RequestMapping(value = "/getFile/{path:.+}", method = RequestMethod.GET)
public File getFile(@PathVariable String path) {
// do something
}
What I did works with relative paths to download/upload files in Spring.
@RequestMapping(method = RequestMethod.GET, path = "/files/**")
@NotNull
public RepositoryFile get(@PathVariable final String repositoryId,
@PathVariable final String branchName,
@RequestParam final String authorEmail,
HttpServletRequest request) {
String filePath = extractFilePath(request);
....
}
And the utilitary function I created within the controller :
private static String extractFilePath(HttpServletRequest request) {
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
AntPathMatcher apm = new AntPathMatcher();
return apm.extractPathWithinPattern(bestMatchPattern, path);
}