下载单个文件
List<FindResultCodeResponse> resultCodeResponseList = resultCodeMapper.getResultCodes(resultCodeRequest);
String resultCodes = JSON.toJSONString(resultCodeResponseList);
response.addHeader("Content-Disposition", "attachment;filename=resultCode.java");
response.setContentType("application/csv;charset=UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.write(resultCodes);
} catch (IOException e) {
e.printStackTrace();
CustomLoggerUtil.printErrorLog(this.getClass(),"downloadNacosFile-下载nacos文件异常=[{}]",e);
}
out.flush();
下载多个文件压缩
public void downloadFile(HttpServletResponse response, List<File> files){
response.setHeader("Content-Disposition", "attachment;fileName=ResultCodeEnum.zip");
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
downloadTolocal(zos,files);
} catch (IOException e) {
CustomLoggerUtil.printErrorLog(this.getClass(),"downloadEnumFile-下载全部文件失败,错误信息=[{}]",e);
}finally {
if(zos != null) {
try {
zos.close();
} catch (Exception e2) {
CustomLoggerUtil.printInfo(this.getClass(),"关闭输入流时出现错误",e2);
}
}
if(outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
CustomLoggerUtil.printInfo(this.getClass(),"关闭输入流时出现错误",e2);
}
}
}
}
private void downloadTolocal(ZipOutputStream zos,List<File> files) throws IOException {
for (File file : files) {
String fileName = file.getName();
InputStream is = null;
BufferedInputStream in = null;
byte[] buffer = new byte[1024];
int len;
ZipEntry entry = new ZipEntry(fileName);
try {
is = new BufferedInputStream(new FileInputStream(file));
in = new BufferedInputStream(is);
zos.putNextEntry(entry);
while ((len = in.read(buffer)) != -1 ) {
zos.write(buffer, 0, len);
}
} catch (Exception e) {
CustomLoggerUtil.printInfo(this.getClass(),"下载全部文件--压缩文件出错",e);
}finally {
if(entry != null) {
try {
zos.closeEntry();
} catch (Exception e2) {
CustomLoggerUtil.printInfo(this.getClass(),"下载全部文件--zip实体关闭失败",e2);
}
}
if(in != null) {
try {
in.close();
} catch (Exception e2) {
CustomLoggerUtil.printInfo(this.getClass(),"下载全部文件--文件输入流关闭失败",e2);
}
}
if(is != null) {
try {
is.close();
}catch (Exception e) {
CustomLoggerUtil.printInfo(this.getClass(),"下载全部文件--输入缓冲流关闭失败",e);
}
}
}
}
}