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

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