如何在Spring Boot 2.0 Web应用程序中为图像存储指定外部位置? [英] How to specify external location for image store in Spring Boot 2.0 web app?
问题描述
目前,我的图像存储在项目目录的/src/main/resources/static/myimages中.现在,我想将它们移动到/Users/tom/myimages中的项目目录之外,以便在HTML标记中的img标签src ="/myimages/subdir/first.jpg"中从/Users/tom/myimages/中加载subdir/first.jpg.如何在Spring Boot 2.0项目中实现这一目标?
Currently I have images stored in /src/main/resources/static/myimages in the project directory. Now I want to move these outside of project directory like in /Users/tom/myimages so that in img tag src="/myimages/subdir/first.jpg" in the HTML markup will be loaded from /Users/tom/myimages/subdir/first.jpg. How can I achieve this in spring boot 2.0 project?
这将允许我添加新图像,而不必在生产环境中重新编译项目.
This will allow me to add new images without having to recompile the project in production environment.
推荐答案
您可以通过PathResourceResolver
实现此目的,这是最简单的解析器,其目的是在给定公共URL模式的情况下查找资源.实际上,这是默认解决方案.
You could achieve this, by PathResourceResolver
which is the simplest resolver and its purpose is to find a resource given a public URL pattern. In fact, this is the default resolve.
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/myimages/**")
.addResourceLocations("/Users/tom/myimages")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
}
说明:
- 我们正在资源链中将
PathResourceResolver
注册为其中唯一的ResourceResolver
. - 与
PathResourceResolver
一起在/Users/tom/myimages
文件夹中找到/first.jpg
文件的html代码 - We are registering the
PathResourceResolver
in the resource chain as the soleResourceResolver
in it. - the html code that, in conjunction with the
PathResourceResolver
, locates the/first.jpg
file in the/Users/tom/myimages
folder
Description:
这篇关于如何在Spring Boot 2.0 Web应用程序中为图像存储指定外部位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!