Springboot访问外部静态文件

废话不多说,代码奉上:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String basePath = "file://" + System.getProperty("user.dir");
        registry.addResourceHandler("/files/**").addResourceLocations(basePath + "\\pic", basePath + "\\packages");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}

即可访问目录下的pic和packages文件夹。
其中,System.getProperty(“user.dir”) 等于“/你的工作目录”。
访问就是http://你的域名/files/文件路径+文件名+后缀就可以了。
例如:http://localhost:8004/files/usr/pic/1.Png

发布了28 篇原创文章 · 获赞 49 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qwe25878/article/details/104364514