实习期间遇见一个小问题,这里记录一下,是前端会传过来一个图片,我一开始想的是前端会传过来图片的url,我直接存数据库,但是应该是我去接收图片,并下载下来,然后获取图片的路径,存到数据库中。我其实还想过一个问题,后面我会将项目部署到服务器上,看了一天的代码脑子昏昏的,一开始竟然想着直接将图片下载到服务器上,后来意识到这个项目最后会部署到服务器上,现在的静态资源,到服务器上也会生成。

  1. 在yaml文件中添加静态文件的路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
file:
upload:
//这里指定存放静态文件的路径
path: src/main/resources/static/images/upload
//这个指定前缀,可有可无
access-path: /images/upload

spring:
web:
resources:
//这里是指定两个静态资源
static-locations:
- classpath:/static/
- file:src/main/resources/static/ //这个可以改成你电脑上任意的目录
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
  1. 添加配置文件,需要将静态资源添加进去
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    //配置类
    @Component
    public class Webconfig implements WebMvcConfigurer {
    @Autowired
    LoginInterceptor loginInterceptor;
    //注册器,将loginInterceptor拦截器注册,只有注册后,每个请求才会先经过拦截器
    @Value("${file.upload.path}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    // 配置静态资源映射
    registry.addResourceHandler("/images/**")
    .addResourceLocations("classpath:/static/images/")
    //这个可以改成你电脑上任意的目录
    .addResourceLocations("file:src/main/resources/static/images/"); // 添加文件系统路径
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    //登录接口不阻拦
    registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/checkCode","/admin/login","/slide/get_show","/images/**");
    }
    }

添加完配置类后,记得在拦截器里添加不拦截的路径,不然也会被拦截下来,访问不到

  1. 结果

下载图片到静态资源的逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public String uploadFile(MultipartFile file) throws IOException {
// 获取根目录
String projectPath = System.getProperty("user.dir");
// 构建完整的上传路径 图片存储的目录
String fullPath = projectPath + "/src/main/resources/static/images/upload/";

// 确保目录存在
File uploadDir = new File(fullPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}

// 生成文件名
String fileName = generateFileName(file.getOriginalFilename());

// 创建目标文件
File destFile = new File(uploadDir, fileName);

// 保存文件
file.transferTo(destFile);

// 返回可访问的URL路径
return "/images/upload/" + fileName;
}