按照输出流方式,会报getOutputStream() has already been called for this response错误,不影响功能。更改如下方式解决:使用ResponseEntity
@RequestMapping(value="/exportJudge")
public ResponseEntity<byte[]> exportJudge(String exportDate,Model model,HttpServletResponse response) {
// String result = "下载完成!请到"+downloadDir+exportDate+".zip中查看";
String result = "下载成功";
File sourceDirectory = new File(saveDir+exportDate);
ResponseEntity<byte[]> responseEntity = null;
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压缩包后,将该压缩包通过输出流发送到客户端
//创建输入流
InputStream is = null;
try {
is = new FileInputStream(zipFile);
//创建字节数组
byte[] buffer = new byte[is.available()];
//将流读到字节数组中
is.read(buffer);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String,String> headers = new HttpHeaders();
//设置要下载方式以及下载文件名字
headers.add("Content-Type", "application/zip");
headers.add("Content-Disposition","attachment;filename=" + exportDate + ".zip");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
responseEntity = new ResponseEntity<>(buffer,headers,statusCode);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭输入流
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("MSG", result);
}
return responseEntity;
}