项目中需要将多个文件打包成压缩包下载。
总共文件是,一个从磁盘读取的文件,其他文件通过url从oss下载的文件,
@GetMapping("/export/{id}")
public void exportById(@PathVariable Integer id,HttpServletResponse response) {
StRecord record = stRecordBiz.selectByPrimaryKey(id);
String filename="单证"+record.getDiagnosisNo();
//xls url
StringBuffer xls = new StringBuffer();
//准备zip
OutputStream outputStream = null;
ZipOutputStream zos = null; //导出的zip输出流
BufferedInputStream bis = null;//从磁盘读文件缓冲
FileInputStream wordIs = null;//从磁盘读文件
//导出word
String wordName = filePath+filename+".doc";//从磁盘读取文件的文件名
ZipEntry entry = new ZipEntry(filename+".doc"); //压缩包中的每一个文件是一个zip
int len;
File file = new File(wordName);
try{ //一下代码是从磁盘读取文件,输出到zip的输出流里
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
wordIs = new FileInputStream(file);
byte[] buffer = new byte[1024*4];
bis = new BufferedInputStream(wordIs);
zos.putNextEntry(entry);
while ((len = bis.read(buffer)) != -1){
zos.write(buffer,0,len);
}
} catch (IOException e) {
log.error("zip 错误", e);
}finally {
if (entry !=null){
try {
zos.closeEntry();
} catch (IOException e) {
log.error(" entry 关闭异常", e);
}
}
try {
bis.close();
} catch (IOException e) {
log.error("BufferedInputStream 关闭异常", e);
}
try {
wordIs.close();
} catch (IOException e) {
log.error("FileInputStream 关闭异常", e);
}
file.delete();//删除临时文件
}
try {
//导出excel
exportExcel(zos,xls); //根据url,输出多个文件
//返回格式
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + new String(filename.getBytes("utf-8"), "iso8859-1") + ".zip\"");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(zos != null){
try {
zos.close();
} catch (IOException e) {
log.error("zos 关闭异常", e);
}
}
try {
outputStream.close();
} catch (IOException e) {
log.error("outputStream 关闭异常", e);
}
}
}
总结:注意关闭流时,按照打开的顺序,倒序关闭。
Original: https://www.cnblogs.com/junnnnnnnn/p/15710332.html
Author: 小小小小青石
Title: java 文件打压缩包下载
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/609426/
转载文章受原作者版权保护。转载请注明原作者出处!