springboot 下载zip压缩包文件
时间: 2023-12-04 08:05:30 浏览: 161
如果你想在Spring Boot中下载一个ZIP压缩文件,你可以使用Java的内置类库或者第三方库来实现。这里有两种实现方式:
1. 使用Java的内置类库
```java
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
String fileName = "example.zip";
String filePath = "/path/to/example.zip";
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
```
2. 使用第三方库
```java
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
String fileName = "example.zip";
String filePath = "/path/to/example.zip";
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Transfer-Encoding", "binary");
try {
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
} finally {
fis.close();
}
}
```
其中,第二种方式使用了Apache Commons IO库中的IOUtils工具类。这个工具类可以很方便地将输入流复制到输出流中。
阅读全文