springboot 自定义上传路径

项目中涉及上传文件时,如果将文件保存到项目路径,一旦重新部署项目就会出现之前上传的文件找不到的情况;因此我们需要将文件保存到项目以外的绝对路径,或者使用单独的服务保存文件,本文介绍如何配置 springboot,使上传的文件保存到项目以外的绝对路径

 

1、在 application.yml 文件中自定义相关配置

为了实现动态配置文件保存路径和文件访问路径,故在 application.yml 文件中添加配置

file:
  path: file/**    #文件访问路径
  address:  D://uploadFiles/  #文件保存路径

 

2、实现 WebMvcConfigurer 接口,重写 addResourceHandlers 方法

自定义 FilePathConfig 类,实现 WebMvcConfigurer 接口

package com.demo.config;

import org.springframework.beans.factory.annotation.Value;
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 FilePathConfig implements WebMvcConfigurer{
	
	@Value("${file.path}")
	private String path;
	
	@Value("${file.address}")
	private String address;
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler(path).addResourceLocations("file:" + address);
	}
}

至此,配置完成

 

3、测试

启动项目

springboot 自定义上传路径_第1张图片

在配置的 D:\uploadFiles 文件夹下保存两张图片

springboot 自定义上传路径_第2张图片

浏览器访问 http://localhost:8080/file/timg.jpg

springboot 自定义上传路径_第3张图片

浏览器访问 http://localhost:8080/file/a.jpg

 

你可能感兴趣的:(spring,boot)