SpringBoot实现文件上传下载
在当今的Web开发中,文件上传与下载功能是众多项目不可或缺的一部分,尤其是在构建内容管理系统、云存储服务或社交平台时。Spring Boot,作为Java领域广受欢迎的框架,以其简洁的配置和强大的功能支持,极大地简化了这一过程。本文将概述如何利用Spring Boot结合Hutool工具库来高效地实现文件上传与下载功能。
文件上传
引入工具依赖
1 2 3 4 5 6
| <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.25</version> </dependency>
|
编写配置文件
1 2 3
| files: upload: path: E:/test/files/
|
编写 Controller
这里仅供展示就全写到 Controller 里了,实际开发中应该根据业务逻辑进行拆分,如果不需要上传数据库,可以省略数据库操作.
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 46 47 48 49 50 51 52 53 54 55 56 57
| @RestController @RequestMapping("/file") public class FileController {
@Value("${files.upload.path}") private String fileUploadPath;
@PostMapping("/upload") public Result upload(@RequestParam("file") MultipartFile file) { String originalFilename = file.getOriginalFilename(); String type = FileUtil.extName(originalFilename); long size = file.getSize() / 1024;
String uuid = IdUtil.fastSimpleUUID(); File uploadFile = new File(fileUploadPath + uuid + StrUtil.DOT + type);
File parentFile = uploadFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); }
String md5; String url; file.transferTo(uploadFile); md5 = SecureUtil.md5(uploadFile); LambdaQueryWrapper<FileDB> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(FileDB::getMd5, md5); if (!fileMapper.selectList(queryWrapper).isEmpty()) { FileUtil.del(uploadFile); return Result.success(fileMapper.selectList(queryWrapper).get(0).getUrl()); } else { url = "http://localhost:8080/file/" + uuid + StrUtil.DOT + type; }
FileDB fileDB = new FileDB(); fileDB.setName(originalFilename); fileDB.setType(type); fileDB.setSize(size); fileDB.setUrl(url); fileDB.setMd5(md5);
fileMapper.insert(fileDB); return Result.success(url); } }
|
文件下载
1 2 3 4 5 6 7 8 9 10 11 12 13
| @GetMapping("/{fileName}") public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException { File file = new File(fileUploadPath + fileName); ServletOutputStream outputStream = response.getOutputStream(); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8)); response.setContentType("application/octet-stream");
outputStream.write(FileUtil.readBytes(file)); outputStream.flush(); outputStream.close(); }
|
其他配置
如果配置了拦截器,可以选择性添加下面配置
1 2 3 4 5 6 7 8 9 10 11
| @Configuration public class WebConfig implements WebMvcConfigurer {
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/**/login/**", "/**/register/**","/file/***") .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v3/**", "/swagger-ui.html/**"); } }
|