gpt4 book ai didi

java - 如何在 Spring Boot 中接受直到 PathVariable 的所有嵌套子目录?

转载 作者:行者123 更新时间:2023-12-02 08:46:13 25 4
gpt4 key购买 nike

背景

我正在尝试访问 classpath:resources/images 中包含的图像。 images 目录中包含子目录。

问题

例如,访问 localhost:<springboot-port>/images/some-sub-directory/some-image.png 时我收到错误:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Apr 06 19:52:20 UTC 2020
There was an unexpected error (type=Not Found, status=404).
SRVE0295E: Error reported: 404

如何以这种方式访问​​子目录中的图像?

代码

@RestController
public class ImagesController {
@CrossOrigin
@RequestMapping(value = "/images/{filePath}", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
public void getImage(@PathVariable("filePath") String filePath, HttpServletResponse response) throws IOException {
response.setContentType(MediaType.IMAGE_PNG_VALUE);
StreamUtils.copy(new ClassPathResource("images/" + filePath).getInputStream(), response.getOutputStream());
}
}

最佳答案

简短:当您调用它时(从浏览器或 postman 或其他任何地方),将 url 的路径变量部分中的“/”替换为“%2F”

在 PathVariable 中使用“/”会阻止 Controller 解析此路径变量:

当您调用localhost:<springboot-port>/images/some-sub-directory/some-image.png时 Controller 尝试与 /images/{var1}/{var2} 匹配路线在哪里var1 = some-sub-directoryvar2 = some-image.png并失败。

我建议您找到一种方法,在要作为路径变量传递的字符串中对“/”进行编码,然后在方法内部对其进行解码,然后才创建所请求图像的 uri。 (用“/”替换您用作代码的任何内容)

关于java - 如何在 Spring Boot 中接受直到 PathVariable 的所有嵌套子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61067975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com