@Autowired
private HttpServletResponse response;
public void downloadFolder(File file){
try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
String fileName = String.format("%s_%s.zip", file.getName(), Constants.FILENAME_DATETIME_FORMAT.format(new Date()));
//不需要设置contentType,会报错;
response.setHeader("Content-disposition", String.format("attachment; filename*=UTF-8''%s", URLEncoder.encode(fileName, "UTF-8")));
downloadFolderData(zipOutputStream, file);
} catch (IOException e) {
log.error("download folder error", e);
}
}
private void downloadFolderData(ZipOutputStream out, File file) throws IOException {
File[] children = file.listFiles();
for (File child: children) {
String fileAbsolutePath = xxx;//获取文件绝对路径
if(!child.isFile()){
downloadFolderData(out, child);
}else{
out.putNextEntry(new ZipEntry(fileAbsolutePath));
InputStream inputStream = xxx //获取文件流
IOUtils.copy(inputStream, out);
out.closeEntry();
}
}
}
zipOutputstream输出到response核心代码
于 2023-05-09 10:31:03 首次发布