springboot 实现文件批量上传与批量下载
时间: 2023-12-11 17:05:58 浏览: 154
Spring Boot 实现文件批量上传与批量下载的步骤如下:
1. 引入相关依赖
在 pom.xml 文件中添加以下依赖:
```xml
<!-- 文件上传 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 文件下载 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 配置上传文件存储路径
在 application.properties 文件中添加以下配置:
```properties
# 上传文件存储路径
file.upload-dir=/path/to/upload/dir
```
3. 实现文件上传
在控制器中添加以下代码:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
// 上传文件存储路径
@Value("${file.upload-dir}")
private String uploadDir;
// 文件上传页面
@GetMapping("/upload")
public String showUploadForm() {
return "upload";
}
// 处理文件上传请求
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("files") List<MultipartFile> files, Model model) {
// 创建上传文件存储路径
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
try {
Files.createDirectories(uploadPath);
} catch (IOException e) {
throw new RuntimeException("Failed to create upload directory", e);
}
}
// 上传文件并保存
List<String> fileNames = files.stream().map(file -> {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
Path filePath = uploadPath.resolve(fileName);
try {
Files.copy(file.getInputStream(), filePath);
} catch (IOException e) {
throw new RuntimeException("Failed to store file " + fileName, e);
}
return fileName;
}).collect(Collectors.toList());
// 返回上传结果
model.addAttribute("message", "Uploaded files: " + fileNames);
return "upload";
}
}
```
上面的代码中,`showUploadForm` 方法返回文件上传页面,`handleFileUpload` 方法处理文件上传请求,将上传的文件保存到指定路径。
上传界面的 HTML 代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<button type="submit">上传</button>
</form>
<div th:if="${message}">
<p th:text="${message}"></p>
</div>
</body>
</html>
```
4. 实现文件下载
在控制器中添加以下代码:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
// 上传文件存储路径
@Value("${file.upload-dir}")
private String uploadDir;
// 文件上传页面
@GetMapping("/upload")
public String showUploadForm() {
return "upload";
}
// 处理文件上传请求
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("files") List<MultipartFile> files, Model model) {
// 创建上传文件存储路径
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
try {
Files.createDirectories(uploadPath);
} catch (IOException e) {
throw new RuntimeException("Failed to create upload directory", e);
}
}
// 上传文件并保存
List<String> fileNames = files.stream().map(file -> {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
Path filePath = uploadPath.resolve(fileName);
try {
Files.copy(file.getInputStream(), filePath);
} catch (IOException e) {
throw new RuntimeException("Failed to store file " + fileName, e);
}
return fileName;
}).collect(Collectors.toList());
// 返回上传结果
model.addAttribute("message", "Uploaded files: " + fileNames);
return "upload";
}
// 文件下载页面
@GetMapping("/download")
public String showDownloadForm(Model model) throws IOException {
// 获取上传的文件列表
Path uploadPath = Paths.get(uploadDir);
List<String> fileNames = Files.list(uploadPath)
.filter(Files::isRegularFile)
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toList());
model.addAttribute("fileNames", fileNames);
return "download";
}
// 处理文件下载请求
@GetMapping("/download")
public ResponseEntity<Resource> handleFileDownload(@RequestParam("fileName") String fileName) throws IOException {
// 获取文件的字节数组
Path uploadPath = Paths.get(uploadDir);
Path filePath = uploadPath.resolve(fileName);
byte[] fileContent = Files.readAllBytes(filePath);
// 创建文件资源
ByteArrayResource resource = new ByteArrayResource(fileContent);
// 返回文件下载响应
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(fileContent.length)
.body(resource);
}
}
```
上面的代码中,`showDownloadForm` 方法返回文件下载页面,`handleFileDownload` 方法处理文件下载请求,将指定文件的字节数组封装成 `ByteArrayResource` 对象,并设置下载响应的头信息。
文件下载页面的 HTML 代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<h1>文件下载</h1>
<ul>
<li th:each="fileName : ${fileNames}">
<a th:href="@{/download(fileName=${fileName})}" th:text="${fileName}"></a>
</li>
</ul>
</body>
</html>
```
上面的代码中,使用了 Thymeleaf 模板引擎,动态生成文件下载链接。
阅读全文