导出zip功能的实现
发布日期:2021-05-07 21:06:08 浏览次数:20 分类:精选文章

本文共 8437 字,大约阅读时间需要 28 分钟。

导出功能实现

前端实现

在前端部分,我们使用了Element UI的按钮组件,并通过点击事件触发导出功能。具体实现如下:

导出本页
downloadNotification() { this.$store .dispatch('downLoadList', this.queryData) .then(res => { const url = URL.createObjectURL(res); const link = document.createElement('a'); link.style.display = 'none'; link.href = url; // 文件名默认使用当前时间戳加上.zip link.setAttribute('download', new Date().getTime() + '.zip'); document.body.appendChild(link); link.click(); });},downLoadList({ commit }, data) { return new Promise((resolve, reject) => { const httpDefault = { method: 'POST', url: DOWNLOADLIST, data: data, responseType: 'blob' }; http(httpDefault) .then(res => { resolve(res); }) .catch(err => { reject(err); }); });}

后端实现

后端主要负责处理数据下载和文件生成。具体实现如下:

public class FileUtils {  public static boolean deleteLocalFile(String sPath) {    boolean flag = false;    File file = new File(sPath);    if (file.isFile() && file.exists()) {      try {        file.delete();      } catch (Exception e) {        e.printStackTrace();      }      flag = true;    }    return flag;  }  public static boolean isImage(String suffix) {    List
imageSuffix = new ArrayList<>(); imageSuffix.add("jpg"); imageSuffix.add("gif"); imageSuffix.add("png"); return imageSuffix.contains(suffix); } public static boolean isVideo(String suffix) { List
videoSuffix = new ArrayList<>(); videoSuffix.add("avi"); videoSuffix.add("mp4"); return videoSuffix.contains(suffix); } public static boolean isImageAndVideo(String suffix) { List
mediaSuffix = new ArrayList<>(); mediaSuffix.add("avi"); mediaSuffix.add("mp4"); mediaSuffix.add("jpg"); mediaSuffix.add("gif"); mediaSuffix.add("png"); return mediaSuffix.contains(suffix); } public static String getFileSuffix(String fileName) { return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); } public static void cutFile(File file1, File file2) { InputStream is = null; OutputStream os = null; byte[] bytes = new byte[1024]; int temp = 0; try { is = new FileInputStream(file1); os = new FileOutputStream(file2); while ((temp = is.read(bytes)) != -1) { os.write(bytes, 0, temp); os.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } file1.delete(); } public static void deleteFile(File file) { try { if (!file.exists()) { return; } if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { deleteFile(f); } } else if (file.isFile()) { file.delete(); } } catch (Exception e) { e.printStackTrace(); } }}

业务逻辑

/downLoadList路由下,我们实现了导出功能的核心业务逻辑:

@PostMapping("/downLoadList")@SuppressWarnings("all")ApiOperation(value = "导出zip", notes = "")public void downLoadList(HttpServletRequest request, HttpServletResponse response, @RequestBody UBo uBo) throws Exception {  // 获取当前页数据  Map
baseData = getList(request, uBo); if ("false".equals(baseData.get("state"))) { return; } // 将记录转换为Excel文件 List
data = (List
) baseData.get("list"); HSSFWorkbook wb = disService.downLoadList(data); // 生成Excel文件 String excelFileDir = new ApplicationHome(getClass()).getSource().getParentFile().toString() + File.separator + "Excel" + File.separator; File dir = new File(excelFileDir); if (!dir.exists()) { dir.mkdirs(); } String excelFileName = RandomUtils.get24TimeRandom() + ".xls"; File excelFile = new File(excelFileDir + File.separator + excelFileName); OutputStream os = new BufferedOutputStream(new FileOutputStream(excelFile)); wb.write(os); os.close(); // 处理图片文件 String picDir = new ApplicationHome(getClass()).getSource().getParentFile().toString() + File.separator + "Pic" + File.separator; FTPUtils fu = new FTPUtils(); FileUtils fileUtils = new FileUtils(); List
files = new ArrayList<>(); for (int i = 0; i < data.size(); i++) { String iStr = Integer.toString(i + 1); File eachPicDir = new File(picDir + File.separator + iStr); if (!eachPicDir.exists()) { eachPicDir.mkdirs(); } String imgUrl = data.get(i).getImgUrl(); String imaUrl = data.get(i).getImaUrl(); String imagUrl = data.get(i).getImagUrl(); if (imgUrl != null && imgUrl.startsWith("http://")) { File file = fu.downUrlFile(imgUrl.substring(imgUrl.lastIndexOf("/") + 1), imgUrl); File target = new File(eachPicDir + File.separator + "xx图片" + iStr + ".jpg"); target.createNewFile(); FileUtils.cutFile(file, target); files.add(target); } if (imaUrl != null && imaUrl.startsWith("http://")) { File file = fu.downUrlFile(imaUrl.substring(imaUrl.lastIndexOf("/") + 1), imaUrl); File target = new File(eachPicDir + File.separator + "xx图片" + iStr + ".jpg"); target.createNewFile(); FileUtils.cutFile(file, target); files.add(target); } if (imagUrl != null && imagUrl.startsWith("http://")) { File file = fu.downUrlFile(imagUrl.substring(imagUrl.lastIndexOf("/") + 1), imagUrl); File target = new File(eachPicDir + File.separator + "xx图片" + iStr + ".jpg"); target.createNewFile(); FileUtils.cutFile(file, target); files.add(target); } // 生成压缩包 String zipPackageDir = new ApplicationHome(getClass()).getSource().getParentFile().toString() + File.separator + "Zip" + File.separator; File zipDir = new File(zipPackageDir); if (!zipDir.exists()) { zipDir.mkdirs(); } String zipPackageName = "myList_" + RandomUtils.get24TimeRandom() + ".zip"; File zipPackage = new File(zipPackageDir + File.separator + zipPackageName); FileOutputStream fos = new FileOutputStream(zipPackage); ZipOutputStream zos = new ZipOutputStream(fos); ZipUtils.zipFile(files, zos); zos.close(); fos.close(); // 下载压缩包 ZipUtils.downloadZip(zipPackage, response); // 删除临时文件 fileUtils.deleteFile(dir); fileUtils.deleteFile(new File(picDir)); fileUtils.deleteFile(zipDir); }}

Excel文件生成

Excel文件的生成逻辑如下:

public HSSFWorkbook downLoadList(List
data) { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("sheet1"); String[] title = { "序号", "xx名称", "xx时间", "xxurl", "xxurl", "xxurl", "姓名", "性别", "身份证号", "xxx", "联系xx", "xx部门", "xx类型", "xx时间", "xx创建人", "xx名称" }; sheet.setDefaultColumnWidth(2000); for (int i = 0; i < title.length; i++) { if ((1 <= i && i <= 5) || i == 8 || i == 10 || i == 11 || i == 13) { sheet.setColumnWidth(i, 4000); } if (i == 1 || i == 2 || i == 13) { sheet.setColumnWidth(i, 5000); } HSSFCell cell = sheet.createRow(0).createCell(i); cell.setCellValue(title[i]); } int index = 1; for (DisBo item : data) { HSSFRow row = sheet.createRow(index); row.createCell(0).setCellValue(index); row.createCell(1).setCellValue(item.getCameraName()); row.createCell(2).setCellValue(item.getCreateTime()); if (libImageUrl != null) { row.createCell(3).setCellValue("xx图片" + indexStr + ".jpg"); } else { row.createCell(3).setCellValue(""); } if (imageUrl != null) { row.createCell(4).setCellValue("xx图片" + indexStr + ".jpg"); } else { row.createCell(4).setCellValue(""); } if (imgUrl != null) { row.createCell(5).setCellValue("xx图片" + indexStr + ".jpg"); } else { row.createCell(5).setCellValue(""); } row.createCell(6).setCellValue(item.getName()); row.createCell(7).setCellValue(item.getGender()); row.createCell(8).setCellValue(item.getIdCard()); row.createCell(9).setCellValue(item.getScore() + "%"); row.createCell(11).setCellValue(item.getAlarmId()); row.createCell(11).setCellValue(item.getApplicantOrg()); row.createCell(12).setCellValue(item.getHitType()); row.createCell(13).setCellValue(item.getAppearTime()); row.createCell(14).setCellValue(item.getCreateUser()); row.createCell(15).setCellValue(item.getLibName()); index++; } return wb;}
上一篇:Object转int报错,解决
下一篇:mybatis的运行原理

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月03日 16时17分06秒