java 在Spring MVC中将文件路径作为@PathVariable发送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38450953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send file path as @PathVariable in Spring MVC
提问by J-Alex
There is a task to pass file path as @PathVariable
in Spring MVC to REST Service with GET
request.
有一项任务是将文件路径与@PathVariable
Spring MVC 中的文件路径一起传递给带有GET
请求的REST 服务。
We can easily do it with POST
sending String of file path in JSON.
我们可以POST
通过在 JSON 中发送文件路径的字符串轻松做到这一点。
How we can do with GET
request and @Controller
like this?
我们如何处理GET
请求并@Controller
像这样?
@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
采纳答案by Byeon0gam
Ok. you use to get pattern. sending get pattern url.
行。你用来获取模式。发送获取模式网址。
Use @RequestParam.
使用@RequestParam。
@RequestMapping(value = "/getFile", method = RequestMethod.GET)
public File getFile(@RequestParam("path") String path) {
// do something
}
and if you use @PathVariable.
如果你使用@PathVariable。
@RequestMapping(value = "/getFile/{path}", method = RequestMethod.POST)
public File getFile(@PathVariable String path) {
// do something
}
回答by Blank
You should define your controller like this:
你应该像这样定义你的控制器:
@RequestMapping(value = "/getFile/{path:.+}", method = RequestMethod.GET)
public File getFile(@PathVariable String path) {
// do something
}
回答by N. Chicoine
What I did works with relative paths to download/upload files in Spring.
我所做的是使用相对路径在 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);
}