第一种方式

1、配置类

package com.offcn.demo.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration//  一个java类  改成一个配置文件的作用  配置类

public class WebMvcConfig implements WebMvcConfigurer {

    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //将所有D:\\springboot\\pic\\ 访问都映射到/myPic/** 路径下

  registry.addResourceHandler("/myPic/**").addResourceLocations("file:E:\\springboot\\pic\\");

    }

}

2、重启项目

例如,在E:/springboot/pic/中有一张1.png图片

在浏览器输入:http://localhost:8080/myPic/1.png即可访问。

 

第二种方式

首先,我们配置application.properties

web.upload-path=D:/springboot/pic/

spring.mvc.static-path-pattern=/**

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/,classpath:/public/,file:${web.upload-path}

注意:

web.upload-path:这个属于自定义的属性,指定了一个路径,注意要以/结尾;

spring.mvc.static-path-pattern=/**:表示所有的访问都经过静态资源路径;

spring.resources.static-locations:在这里配置静态资源路径,前面说了这里的配置是覆盖默认配置,所以需要将默认的也加上否则static、public等这些路径将不能被当作静态资源路径,在这个最末尾的file:${web.upload-path}之所有要加file:是因为指定的是一个具体的硬盘路径,其他的使用classpath指的是系统环境变量。

然后,重启项目

例如,在E:/springboot/pic/中有一张1.png图片

在浏览器输入:http://localhost:8080/1.png 即可访问。

posted on 2019-11-04 22:53  我变秃了但还没变强啊  阅读(2193)  评论(0编辑  收藏  举报