- 如果使用springboot内置的tomcat时
@Configuration
public class WebTomcatVirtualPathConfig implements WebMvcConfigurer {
@Value("${tomcat.virtual.path}")
private String resourceHandler;
@Value("${basePath}")
private String resourceLocations;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(resourceHandler).addResourceLocations("file:///" + resourceLocations + "/");
}
}
application.properties文件中增加:
#访问该链接时,经过静态资源路径
tomcat.virtual.path=/upload/virtual/**
#文件在磁盘上实际存储路径
basePath=C:/Users/mawt/Desktop/im/upload-basepath
测试:访问图片路径为http://192.168.1.145:8088/upload/virtual/10047.jpg
- idea中使用外部tomcat启动时(跟上面的配置没有关系)
在tomcat的conf/server.xml中增加如下内容(加粗内容):
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- 设置图片虚拟路径[访问时路径为/upload/virtual] -->
<Context path="/upload/virtual" docBase="C:/Users/mawt/Desktop/im/upload-basepath" reloadable="true" />
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
打上勾勾,如此便可以实现