1.适用场景: 无需将文件先压缩zip再下载方式,直接读取文件并压缩下载
maven依赖
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency>
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* description:
*/
@RestController
@Slf4j
public class ZipController {
@RequestMapping(value = "getZipFile")
public void getZipFile(HttpServletResponse response) {
/**
* 无需将已有文件进行压缩方式处理
*/
List<String> filePath = new ArrayList<>();
filePath.add("D:\\data\\pdf\\1.pdf");
filePath.add("D:\\data\\pdf\\2.pdf");
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream);) {
for (String s : filePath) {
File file = new File(s);
if (file.exists()) {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
zos.putNextEntry(new ZipEntry(file.getName()));
//使用tomcat下的或者其他IOUtils
org.apache.commons.io.IOUtils.copy(bis, zos);
zos.closeEntry();
}
}
zos.finish(); //解决CRS校验失败问题
String downloadZipFileName = java.net.URLEncoder.encode("查询信息" + System.currentTimeMillis() + ".zip", StandardCharsets.UTF_8.toString());
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + downloadZipFileName);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.close();
} catch (Exception e) {
log.error("getZipFile下载异常:{}", e.getMessage());
}
}
}