SpringBoot访问图片本地路径并映射成url

1、全局配置方式: 

 

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 WebConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //和页面有关的静态目录都放在项目的static目录下
      registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        //上传的图片在F盘下的uploads目录下,访问路径如:http://localhost:8080/images/2021-05-31/d06a63fd-7245-4dc5-9acc-dc5e001af45e.jpg
        //其中images表示访问的前缀。"file:F:/uploads/"是文件真实的存储路径
        registry.addResourceHandler("/images/**").addResourceLocations("file:F:/uploads/");
    }
}

运行该工程:可以发现资源文件夹static也被放入了部署的target文件夹中;

SpringBoot访问图片本地路径并映射成url_第1张图片

通过以下网址均可访问相关静态资源:

http://localhost:8080/static/2021-05-31/d06a63fd-7245-4dc5-9acc-dc5e001af45e.jpg

http://localhost:8080/images/2021-05-31/d06a63fd-7245-4dc5-9acc-dc5e001af45e.jpg

2、yml配置文件方式:

spring:
  mvc:
    static-path-pattern: /images/**
  resources:
    static-locations: file:F:/upload/
file:
  #文件上传的绝对路径
  baseFilePath: F:/upload/
  #项目根路径下的前缀路径
  uploadPathPrefix: /images/

http://localhost:8080/images/2021-05-31/d06a63fd-7245-4dc5-9acc-dc5e001af45e.jpg

你可能感兴趣的:(JAVA,SpringBoot,本地图片,映射,url)