Send file path as @PathVariable in Spring MVC

2019-05-03 06:05发布

问题:

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

回答1:

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
}


回答2:

You should define your controller like this:

@RequestMapping(value = "/getFile/{path:.+}", method = RequestMethod.GET)
public File getFile(@PathVariable String path) {
    // do something
}


回答3:

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