java下载文件压缩zip,并且分文件夹
这两种差不多,取路径的时候有点区别:
第一种:
点击查看代码
public static void downloadFileByFastDFS(@NotNull List<AttachmentFileDto> attachmentFileDtos, HttpServletRequest request,
HttpServletResponse response) {
String localFilePath = "";
String characterEncoding = request.getCharacterEncoding();
log.info("characterEncoding{}", characterEncoding);
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
List<Map<String,String>> files = new ArrayList<>();
FileInputStream in = null;
FileInputStream fis = null;
OutputStream outResponse = null;
BufferedInputStream bufferedInputStream = null;
ZipOutputStream zos = null;
try {
File localFile = new File("");
localFilePath = localFile.getCanonicalPath();
if (CollectionUtils.isEmpty(attachmentFileDtos)) {
throw new ServiceException(AppErrorCode.DataNotExisted.getErrorCode(), "没有需要下载的文件");
}
response.setHeader("content-disposition",
"attachment;fileName=" + URLEncoder.encode(
"附件批量下载".concat(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")).concat(".zip"),
characterEncoding));
try {
Map<String,Integer> nameCount = new HashMap<>();// 计算相同名字的文件数
for (AttachmentFileDto attachmentFileDto : attachmentFileDtos) {
String filePath = attachmentFileDto.getFilePath();
if (StringUtils.isBlank(filePath))
throw new ServiceException(AppErrorCode.DataNotExisted.getErrorCode(), "文件路径不可为空");
// 下载文件名称
String fileName = attachmentFileDto.getName();
if (StringUtils.isBlank(fileName))
throw new ServiceException(AppErrorCode.DataNotExisted.getErrorCode(), "文件名称不可为空");
// 重复名称处理
if(nameCount.containsKey(fileName)){
nameCount.replace(fileName,null != nameCount.get(fileName) ? nameCount.get(fileName)+1:1);
}else{
nameCount.put(fileName,1);
}
if(null != nameCount && null != nameCount.get(fileName) && nameCount.get(fileName)>1){
fileName = fileName.substring(0,fileName.indexOf("."))+"("+nameCount.get(fileName)+")"+ fileName.substring(fileName.indexOf("."),fileName.length());
}
File file = new File(FilenameUtils.normalize(filePath));
byte[] bytesArray = new byte[(int) file.length()];
fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
Map<String, String> maps = new HashMap<>();
maps.put("fileName", fileName);
maps.put("wjj", attachmentFileDto.getWjj());
String encoded = Base64.getEncoder().encodeToString(bytesArray);
maps.put("file", encoded);
files.add(maps);
}
}catch (FdfsServerException fdsExce){
throw new ServiceException(500,"找不到文件位置,下载失败");
}
long start = System.currentTimeMillis();
outResponse = response.getOutputStream();
try {
zos = new ZipOutputStream(outResponse);
for (Map<String,String> map : files) {
byte[] buf = new byte[2048];
String newFileName = map.get("wjj")+"/"+map.get("fileName");// 分文件夹,只要这里zipEntry增加文件夹就可以
zos.putNextEntry(new ZipEntry(newFileName));
// zos.putNextEntry(new ZipEntry(map.get("fileName")));
int len;
File file = new File(map.get("fileName"));
try(OutputStream output = new FileOutputStream(file);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output)) {
bufferedOutput.write(Base64.getDecoder().decode(map.get("file")));
in = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(in);
while ((len = bufferedInputStream.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
zos.flush();
bufferedInputStream.close();
in.close();
// bufferedOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
outResponse.flush();
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null != zos){
try{
zos.close();
}catch (Exception e) {
log.info("testDownload close OutputStream occurs exception:" + e.getMessage());
}
}
if(null != outResponse){
try{
outResponse.close();
}catch (Exception e) {
log.info("testDownload close OutputStream occurs exception:" + e.getMessage());
}
}
for (Map<String, String> fileMap : files) {
File file = new File(localFilePath + "/" + fileMap.get("fileName"));
if (file.exists()){
if (!file.delete()){
log.info("删除失败");
}
}
}
}
}
第二种:
点击查看代码
public Result<?> exportTxt(@RequestBody ThesisCheckApplyDto studentOpenTitleApplyDto) {
List<ThesisCheckApplyVo> list = studentThesisCheckApplyService.quertTxt(studentOpenTitleApplyDto);
String schoolCode = thesisCheckApplyMapper.quertSchoolCode();
String downloadName = (CollectionUtils.isNotEmpty(list) ?list.get(0).getThesisBatchName():"")+"机检txt下载" + ".zip";
response.setContentType("application/zip;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + Encodes.urlEncode(downloadName));
FileOutputStream fileOutputStream = null;
File file = null;
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
// 按学院分组分文件夹
if(CollectionUtils.isEmpty(list)){
// throw new ControllerException(300,"暂无数据导出");
try (
OutputStream outputStream = response.getOutputStream();
// 压缩流
ZipOutputStream zos = new ZipOutputStream(outputStream);) {
String excelName = "未查到学生数据.txt" ;// txt文件名
byte[] buffer = new byte[1024];
int len;
String realPath = request.getSession().getServletContext().getRealPath("");
String filePath = realPath + "/" + excelName;
fileOutputStream = new FileOutputStream(filePath);// 导出路径
// 写内容
fileOutputStream.write("暂无数据导出".getBytes());
file = new File(filePath);
ZipEntry zEntry = new ZipEntry( excelName);
fileInputStream = new FileInputStream(filePath);
bufferedInputStream = new BufferedInputStream(fileInputStream);// 文件输出
zos.putNextEntry(zEntry);// 加入压缩包
while ((len = bufferedInputStream.read(buffer)) != -1) {
zos.write(buffer, 0, len);
zos.write(buffer, 0, len);
}
zos.flush();
zos.close();
} catch (FileNotFoundException e) {
log.error("文件不存在!");
} catch (IOException e) {
log.error("输出流发生错误!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
if (file.exists()) {
boolean delete = file.delete();
if (!delete) {
log.error("context", file.getName() + "删除失败");
}
}
}
try {
if (bufferedInputStream != null) {
bufferedInputStream.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
List<String> departIds = list.stream().map(ThesisCheckApplyVo::getStudentDepartmentId).distinct().collect(Collectors.toList());
Map<String, List<ThesisCheckApplyVo>> map = list.stream().collect(Collectors.groupingBy(k -> k.getStudentDepartmentId() ));
if(null != map && CollectionUtils.isNotEmpty(departIds)){
try (
OutputStream outputStream = response.getOutputStream();
// 压缩流
ZipOutputStream zos = new ZipOutputStream(outputStream);) {
for (String key : departIds) {
List<ThesisCheckApplyVo> list_departItem = map.get(key);
for (ThesisCheckApplyVo vo : list_departItem) {
// 学校代码_学号_ZY.txt
String excelName = (StringUtils.isNotBlank(schoolCode) ? schoolCode: "学校代码")+"_"+vo.getStudentId() + "_ZY.txt" ;// txt文件名
byte[] buffer = new byte[1024];
int len;
String realPath = request.getSession().getServletContext().getRealPath("");
String filePath = realPath + "/" + excelName;
fileOutputStream = new FileOutputStream(filePath);// 导出路径
// 写内容
fileOutputStream.write(vo.getPaperSummary().getBytes());
file = new File(filePath);
ZipEntry zEntry = new ZipEntry( vo.getStudentDepartmentName()+"/"+excelName);
fileInputStream = new FileInputStream(filePath);
bufferedInputStream = new BufferedInputStream(fileInputStream);// 文件输出
zos.putNextEntry(zEntry);// 加入压缩包
while ((len = bufferedInputStream.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
}
}
zos.flush();
zos.close();
} catch (FileNotFoundException e) {
log.error("文件不存在!");
} catch (IOException e) {
log.error("输出流发生错误!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
if (file.exists()) {
boolean delete = file.delete();
if (!delete) {
log.error("context", file.getName() + "删除失败");
}
}
}
try {
if (bufferedInputStream != null) {
bufferedInputStream.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Result.buildSuccessResult();
}
posted on 2025-12-26 14:20 HeavenTang 阅读(2) 评论(0) 收藏 举报
浙公网安备 33010602011771号