SpringBoot实现文件上传下载
灰羽 Lv3

SpringBoot实现文件上传下载

在当今的Web开发中,文件上传与下载功能是众多项目不可或缺的一部分,尤其是在构建内容管理系统、云存储服务或社交平台时。Spring Boot,作为Java领域广受欢迎的框架,以其简洁的配置和强大的功能支持,极大地简化了这一过程。本文将概述如何利用Spring Boot结合Hutool工具库来高效地实现文件上传与下载功能。

文件上传

引入工具依赖

1
2
3
4
5
6
<!-- hutool -->
<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();
// 定义文件存储路径
// 这里使用uuid作为文件名,防止文件重名
// 文件存储路径为:E:/test/files/ + uuid + 文件类型
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
md5 = SecureUtil.md5(uploadFile);
// 查询md5是否存在
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/**");
}
}