SpringBoot系列-文件上传处理

前言

SpringBoot开发遇到文件上传的问题,getRealPath(“/upload”)在SpringBoot中对应的路径在tmp目录下,每次启动都会改变,不再适合保存文件。本文记录下SpringBoot框架下上传文件到自定义目录并生成对应可存储的网络路径方法。

步骤1

application.properties中添加本地路径的配置

1
upload.path = H:/images

步骤二

创建类继承WebMvcConfigurerAdapter并添加路径映射

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class MyWebConfigurer
extends WebMvcConfigurerAdapter {

@Autowired
private Environment env;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + env.getProperty("upload.path") + "/");
super.addResourceHandlers(registry);
}

}

步骤三

上传文件处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@Controller
public class UploadController {

// The Environment object will be used to read parameters from the
// application.properties configuration file
@Autowired
private Environment env;

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
@RequestParam("file") MultipartFile multipartFile) {

/**获取配置的本地路径* */
String rootPathDir = env.getProperty("upload.path");
/**构建按照日期存储的本地路径**/
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/HH");
String fullPathDir = rootPathDir + File.separator + dateFormat.format(new Date());
/**根据本地路径创建目录**/
File fullPathFile = new File(fullPathDir);
if (!fullPathFile.exists())
fullPathFile.mkdirs();
/** 获取文件的后缀* */
String suffix = multipartFile.getOriginalFilename().substring(
multipartFile.getOriginalFilename().lastIndexOf("."));
/** 使用UUID生成文件名称* */
String fileName = UUID.randomUUID().toString() + suffix;
/** 拼成完整的文件保存路径加文件* */
String filePath = fullPathFile + File.separator + fileName;
/** 文件输出流* */
File file = new File(filePath);
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream stream = new BufferedOutputStream(fileOutputStream)) {
stream.write(multipartFile.getBytes());
/** 打印出上传到服务器的文件的本地路径和网络路径* */
System.out.println("****************" + filePath + "**************");
System.out.println("/images/" + dateFormat.format(new Date()) + "/" + fileName);
} catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}
}

运行结果

控制台输出,网络路径用于存储到数据库

1
2
****************H:\images\2016\06\14\08\489b66e4-438b-443a-ab21-5c93de35ae9a.jpg**************
/images/2016/06/14/08/489b66e4-438b-443a-ab21-5c93de35ae9a.jpg

参考

SpringMVC—>Controller获得上传文件的绝对路径

Spring Boot 静态资源处理

spring boot应用启动原理分析