1.application.properties配置
#静态资源对外暴露的访问路径
file.staticAccessPath=/upload/**
#文件上传目录
file.uploadFolder=D:/upload/
2.配置文件实体化
package com.example.demo.upload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
@Configuration
<!--此注解可以
@Configuration底层是含有@Component ,所以@Configuration 具有和 @Component 的作用。
@Configuration可理解为用spring的时候xml里面的<beans>标签。
@Configuration注解可以达到在Spring中使用xml配置文件的作用。
@Bean可理解为用spring的时候xml里面的标签
-->
@ConfigurationProperties(prefix="file")
<!--
此注解可以映射配置文件中所有以'file'开头的文件,相对于 @Configuration ,更加的集中一
-->
public class UploadFilePathConfig implements WebMvcConfigurer {
@Value("${server.port}")
private String port;
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
/**
* 重写这个方法即可配置虚拟路径
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getStaticAccessPath() {
return staticAccessPath;
}
public void setStaticAccessPath(String staticAccessPath) {
this.staticAccessPath = staticAccessPath;
}
public String getUploadFolder() {
return uploadFolder;
}
public void setUploadFolder(String uploadFolder) {
this.uploadFolder = uploadFolder;
}
}
3.调用
使用@autowired即可
此时访问的路径就是:http://localhost:8008/upload/图片名