springboot导出zip
时间: 2025-03-18 20:14:28 浏览: 46
### Spring Boot 实现 ZIP 文件导出的功能
在 Spring Boot 中实现 ZIP 文件的导出功能可以通过创建一个控制器来处理 HTTP 请求,并将多个文件打包成 ZIP 格式返回给客户端。以下是完整的解决方案:
#### 控制器代码示例
下面是一个基于 Spring Boot 的控制器示例,用于导出 ZIP 文件。
```java
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
public class FileExportController {
@GetMapping("/export-zip")
public ResponseEntity<byte[]> exportZip() {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {
// 添加第一个文件到 ZIP 压缩包中
String content1 = "This is the content of file1.txt";
addFileToZip(zipOutputStream, "file1.txt", content1);
// 添加第二个文件到 ZIP 压缩包中
String content2 = "This is the content of file2.txt";
addFileToZip(zipOutputStream, "file2.txt", content2);
byte[] zipBytes = byteArrayOutputStream.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=files.zip");
return new ResponseEntity<>(zipBytes, headers, HttpStatus.OK);
} catch (IOException e) {
throw new RuntimeException("Error while creating zip archive", e); // 异常处理逻辑[^1]
}
}
private void addFileToZip(ZipOutputStream zipStream, String fileName, String content) throws IOException {
ZipEntry entry = new ZipEntry(fileName);
zipStream.putNextEntry(entry);
zipStream.write(content.getBytes());
zipStream.closeEntry();
}
}
```
上述代码定义了一个 RESTful API `/export-zip`,当访问该接口时会生成并返回一个包含两个文本文件 (`file1.txt`, `file2.txt`) 的 ZIP 文件。
#### 测试类代码示例
为了验证此功能是否正常工作,可以编写如下测试代码:
```java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(FileExportController.class)
public class FileExportControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testExportZip() throws Exception {
this.mockMvc.perform(get("/export-zip"))
.andExpect(status().isOk()); // 验证状态码为 200 OK[^2]
}
}
```
这段代码展示了如何使用 JUnit 和 Spring MVC Test 工具对控制器方法进行单元测试。
---
### 注意事项
- 如果需要动态读取磁盘上的实际文件而不是字符串内容,则应调整 `addFileToZip` 方法以支持流操作。
- 对于较大的文件集合或高并发场景,建议优化内存管理策略,例如采用分块写入的方式减少内存占用。
---
阅读全文
相关推荐

















