工具类:
package com.lenovo.tdp.inbox.common.utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author wxm
*/
public class FileZipUtil {
private static void handlerFile(ZipOutputStream zip, File file, String dir) throws Exception {
//如果当前的是文件夹,则进行进一步处理
if (file.isDirectory()) {
//得到文件列表信息
File[] fileArray = file.listFiles();
if (fileArray == null) {
return;
}
//将文件夹添加到下一级打包目录
zip.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
//递归将文件夹中的文件打包
for (File f : fileArray) {
handlerFile(zip, f, dir + f.getName());
}
} else {
//当前的是文件,打包处理
//文件输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(dir);
zip.putNextEntry(entry);
zip.write(FileUtils.readFileToByteArray(file));
IOUtils.closeQuietly(bis);
zip.flush();
zip.closeEntry();
}
}
private static byte[] createZip(String sourceFilePath) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
//将目标文件打包成zip导出
File file = new File(sourceFilePath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
handlerFile(zip, file, "");
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
public static void exportZip(HttpServletResponse response, String sourceFilePath,String appId) {
//文件名以时间戳作为前缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filePrefix = sdf.format(new Date());
String downloadName =appId+filePrefix + ".zip";
//将文件进行打包下载
try {
OutputStream out = response.getOutputStream();
//接收压缩包字节
byte[] data = createZip(sourceFilePath);
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + downloadName);
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
IOUtils.write(data, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1、controller
public static final String sign = "/";
//模板导出
@RequestMapping(value = "/export", method = {RequestMethod.POST})
@ResponseBody
public IResponse<Object> templateExportToFile(HttpServletResponse response, @RequestParam String appId, @RequestParam(required = false) String ids) {
try {
//String realPath = request.getSession().getServletContext().getRealPath("/");
//String filePath = new File(realPath).getParent()+ "\\temp";
String filePath = "./tmp/" + appId + "-" + String.valueOf(System.currentTimeMillis());
//String filePath = "D:\\wxm\\templates";
File root = new File(filePath);
if (!root.exists() && !root.isDirectory()) {
root.mkdirs();
}
//模板列表
List<BizInfo> templateList = bizInfoService.templateExportToFeil(response, appId, ids);
//判空
if (CollectionUtils.isEmpty(templateList)) {
return failed(ErrorEnum.FILE_NULL.getResultCode(), ErrorEnum.FILE_NULL.getResultMsg());
}
for (BizInfo bizInfo : templateList) {
//模板内容列表
List<MailTemplateInfo> templateInfoList = mailTemplateInfoService.getListByBizId(bizInfo.getId());
File file = new File(filePath + sign + bizInfo.getBizName());
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
//组装模板数据
BizInfoExportDTO bizInfoExportDTO = new BizInfoExportDTO();
BeanUtils.copyProperties(bizInfo, bizInfoExportDTO);
FileUtil.writeString(JSON.toJSONString(bizInfoExportDTO), filePath + sign + bizInfo.getBizName() + sign + "bizInfo.json", "UTF-8");
System.out.println("模板集json: " + JSON.toJSONString(bizInfoExportDTO));
//组装模板下内容数据
if (!CollectionUtils.isEmpty(templateInfoList)) {
List<MailTemplateInfoExportDTO> mailTemplateInfoList = templateInfoList.stream().map(temp -> {
MailTemplateInfoExportDTO dto = new MailTemplateInfoExportDTO();
BeanUtils.copyProperties(temp, dto);
dto.setBizName(bizInfo.getBizName());
return dto;
}).collect(Collectors.toList());
FileUtil.writeString(JSON.toJSONString(mailTemplateInfoList), filePath + sign + bizInfo.getBizName() + sign + "templateInfo.json", "UTF-8");
System.out.println("模板内容json: " + JSON.toJSONString(mailTemplateInfoList));
}
}
FileZipUtil.exportZip(response, filePath,appId);
// BizAndTempExportRespDTO ans = new BizAndTempExportRespDTO();
// ans.setLink(filePath);
FileUtil.del(filePath);
return success();
} catch (Exception e) {
log.error("/biz.getOne error,message={}", e.getMessage());
return failed(ErrorEnum.INTERNAL_SERVER_ERROR.getResultCode(), ErrorEnum.INTERNAL_SERVER_ERROR.getResultMsg());
}
}
2、service
//模板导出
List<BizInfo> templateExportToFeil(HttpServletResponse response,String appId, String ids) throws IOException;
@Override//xm
public List<BizInfo> templateExportToFeil(HttpServletResponse response,String appId, String ids) throws IOException {
//根据appId/获取需要导出模板数据
QueryWrapper<BizInfo> condition = new QueryWrapper<>();
condition.eq("app_id",appId);
if (!Strings.isBlank(ids)) {
String[] split = ids.split(",");
condition.in("id", Arrays.stream(split).map(s -> Integer.valueOf(s)).collect(Collectors.toList()));
}
List<BizInfo> templateList = this.list(condition);
return templateList;
}