前言 SpringBoot开发遇到文件上传的问题,getRealPath(“/upload”)在SpringBoot中对应的路径在tmp目录下,每次启动都会改变,不再适合保存文件。本文记录下SpringBoot框架下上传文件到自定义目录并生成对应可存储的网络路径方法。
步骤1 application.properties 中添加本地路径的配置
步骤二 创建类继承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 { @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("." )); 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应用启动原理分析