目录
标签:上传.下载.Excel.导入.导出;
一、简介
在项目中,文件管理是常见的复杂功能;
首先文件的类型比较多样,处理起来比较复杂,其次文件涉及大量的IO操作,容易引发内存溢出;
不同的文件类型有不同的应用场景;
比如:图片常用于头像和证明材料;Excel偏向业务数据导入导出;CSV偏向技术层面数据搬运;PDF和Word用于文档类的材料保存等;
下面的案例只围绕普通文件和Excel两种类型进行代码实现;
二、工程搭建
1、工程结构
2、依赖管理
普通文件的上传下载,依赖spring-boot
框架即可,而Excel类型选择easyexcel
组件,该组件内部依赖了apache-poi
组件的4.1.2
版本;
<!-- 基础框架组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- Excel组件 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
三、上传下载
1、配置管理
在配置文件中,添加max-file-size
单个文件大小限制和max-request-size
请求最大限制两个核心参数;
需要说明的一点是:如何设定参数值的大小,与业务场景和服务器的处理能力都有关系,在测试的过程中优化即可;
spring:
# 文件配置
servlet:
multipart:
enabled: true
# 文件单个限制
max-file-size: 10MB
# 请求最大限制
max-request-size: 20MB
2、上传下载
这里提供一个文件批量上传接口和一个文件下载接口,把文件管理在工程中的resources/file
目录下,下载接口中需要指定该目录下的文件名称;
@RestController
public class FileWeb {
private static final Logger logger = LoggerFactory.getLogger(FileWeb.class);
@Resource
private FileService fileService ;
/**
* 文件上传
*/
@PostMapping("/file/upload")
public String upload (HttpServletRequest request,
@RequestParam("file") MultipartFile[] fileList) throws Exception {
String uploadUser = request.getParameter("uploadUser");
if (uploadUser.isEmpty()){
return "upload-user is empty";
}
logger.info("upload-user:{}",uploadUser);
for (MultipartFile multipartFile : fileList) {
// 解析文件信息和保存
fileService.dealFile(multipartFile);
}
return "success" ;
}
/**
* 文件下载
*/
@GetMapping("/file/download")
public void upload (@RequestParam("fileName") String fileName,
HttpServletResponse response) throws Exception {
if (!fileName.isBlank()){
String filePath = ResourceUtils.getURL("m1-04-boot-file/src/main/resources/file").getPath();
File file = new File(filePath,fileName) ;
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
response.setContentType("application/octet-stream");
Files.copy(Paths.get(file.getPath()), response.getOutputStream());
}
}
}
/**
* 文件服务类
*/
@Service
public class FileService {
private static final Logger logger = LoggerFactory.getLogger(FileService.class);
public void dealFile (MultipartFile multipartFile) throws Exception {
logger.info("Name >> {}",multipartFile.getName());
logger.info("OriginalFilename >> {}",multipartFile.getOriginalFilename());
logger.info("ContentType >> {}",multipartFile.getContentType());
logger.info("Size