根据路径将其文件打包压缩成zip包,并导出到浏览器上。支持多个文件打包。
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.http.HttpHeaders;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public void downloadZip(HttpServletResponse response) {
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"files.zip\"");
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
//如果导出的文件数量不确定,可自己加入for循环调用下面的addToZip()
addToZip("/home/files/template/111.pdf", zipOut);
addToZip("/home/files/template/222.pdf", zipOut);
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 处理zip文件下载
* @param filePath 待打包的文件路径信息
* @return
*/
private void addToZip(String filePath, ZipOutputStream zipOut) throws IOException {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
zipOut.closeEntry();
}
至此为止,一次性导出多个文件到zip包中已完成。