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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章