@GetMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) {
log.info("come in... ");
BufferedInputStream inputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ZipOutputStream zipOutputStream = null;
try {
response.setContentType("application/octet-stream");
String fileName = "20201013.zip";
// 中文乱码问题
// response.addHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes(), "ISO-8859-1"));
response.addHeader("Content-disposition", "attachment;filename="+java.net.URLEncoder.encode(fileName.trim(), "UTF-8"));
bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
zipOutputStream = new ZipOutputStream(bufferedOutputStream);
byte[] bs = new byte[1024];
int len = 0;
File[] files = new File("E:\\zhoulp\\202010").listFiles();
for (File file : files) {
String zipEntryName = file.getName();
inputStream = new BufferedInputStream(new FileInputStream(file));
ZipEntry zipEntry = new ZipEntry(zipEntryName);
zipOutputStream.putNextEntry(zipEntry);
while ( (len = inputStream.read(bs) ) > 0 ) {
zipOutputStream.write(bs, 0, len);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(zipOutputStream != null) {
zipOutputStream.closeEntry();
zipOutputStream.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if(inputStream != null) {
inputStream.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}