需求:服务器有个以日期为文件名的文件夹,该文件夹下存储多个学生的讲师评价,教师需要将所有学生的讲师评价下载到本地。
思路:将文件夹下所有讲师评价文件打包成压缩包,压缩包暂存到服务器上,然后将压缩包通过输出流下载到客户本地
@RequestMapping(value="/exportJudge")
public String exportJudge(String exportDate,Model model,HttpServletResponse response) {
// String result = "下载完成!请到"+downloadDir+exportDate+".zip中查看";
String result = "下载成功";
File sourceDirectory = new File(saveDir+exportDate);
if(!sourceDirectory.exists()){
model.addAttribute("MSG", "该日期没有学员提交讲师评价文件");
}else{//将目录下所有excel打包成zip压缩包,按照日期命名压缩包文件名
File[] fileArr = sourceDirectory.listFiles();
File downFile = new File(downloadDir);
if(!downFile.exists()){
downFile.mkdir();
}
File zipFile = new File(downloadDir+exportDate+".zip");
ZipOutputStream zipStream = null;
FileInputStream zipSource = null;
BufferedInputStream bufferStream = null;
try {
zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
for(File fileTemp:fileArr){
File file = new File(fileTemp.getAbsolutePath());
//将需要压缩的文件格式化为输入流
zipSource = new FileInputStream(file);
//压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样
ZipEntry zipEntry = new ZipEntry(file.getName());
//定位该压缩条目位置,开始写入文件到压缩包中
zipStream.putNextEntry(zipEntry);
//输入缓冲流
bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
int read = 0;
//创建读写缓冲区
byte[] buf = new byte[1024 * 10];
while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1){
zipStream.write(buf, 0, read);
}
}
} catch (FileNotFoundException e) {
result = "下载失败";
e.printStackTrace();
} catch (IOException e) {
result = "下载失败";
e.printStackTrace();
}finally {
//关闭流
try {
if(null != bufferStream) bufferStream.close();
if(null != zipStream) zipStream.close();
if(null != zipSource) zipSource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if("下载成功".equals(result)){ //在服务器生成zip压缩包后,将该压缩包通过输出流发送到客户端
response.setContentType("application/zip");
//响应头部
response.setHeader("Content-disposition", "attachment;filename=" + exportDate + ".zip");
FileInputStream fis = null;
ServletOutputStream os = null;
try {
fis = new FileInputStream(zipFile);
os = response.getOutputStream();
IOUtils.copy(fis, os);
} catch (FileNotFoundException e) {
result = "下载失败";
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
result = "下载失败";
e.printStackTrace();
}finally{
try {
if(fis!=null){fis.close();}
if(os!=null){os.close();}
zipFile.delete(); //删除掉服务器生成的压缩包文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("MSG", result);
}
return "studentJudge";
}