为静态资源提供网络映射服务

阅读 67

2022-01-24

让本地服务器,也就是localhost,可以直接在浏览器里输入http://localhost/XXX访问本地的图片

写一个WebMvcConfig类实现WebMvcConfigurer类的addResourceHandlers方法

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 用于配置restTemplate
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    //实现静态资源的映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/META-INF/resources/")  //在没加本地头像图片映射时,swagger2是可以直接被浏览器访问的,会自动加。但加了之后,swagger2也需要配置映射
                .addResourceLocations("file:/src/photo/");
                //映射本地头像上传地址file:///D:/src/photo/
                //可以直接在http://localhost:8088/访问D:/src/photo/下的图片文件
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }

}
file:///D:/src/photo这里就是你本地图片上传的位置

结果:

 

精彩评论(0)

0 0 举报