本章介绍如何访问服务器静态资源,它不是Resource的静态资源。

下面介绍如何能访问到服务器的静态资源,其实很简单,只需要一个配置文件即可。

package com.example.yxjc.config;

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 WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploads/**").addResourceLocations("file:C:/uploads/");
    }
} 
/uploads/是url地址,file:C:/uploads/是服务器的路径

重启服务,在C:/uploads/l路径存放一张图片,输入地址:http://localhost:8080/uploads/1.png

SpringBoot图片或文件资源访问

如果要映射多个地址呢,也很简单?

只需要将上面的

registry.addResourceHandler("/uploads/**").addResourceLocations("file:C:/uploads/");

改为

registry.addResourceHandler("/uploads/**","/up2/***").addResourceLocations("file:C:/uploads/","file:C:/up2/");