public ResponseEntity getTaizhangZip() throws IOException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String date = simpleDateFormat.format(new Date()); String filesrc = "D://hydd/tz"; String zipFilesrc = "D://hydd//"+date+".zip"; // 创建一个文件夹 File file = new File(filesrc); file.mkdirs(); List<HyddTaizhang> taizhangList = iHyddTaizhangService.list(); for (HyddTaizhang hyddTaizhang:taizhangList) { //每个日期创建一个文件夹 String datesrc = simpleDateFormat.format(hyddTaizhang.getTzDate()); String src = filesrc+"//"+datesrc+"//"+hyddTaizhang.getXh(); log.info(src); file = new File(src); file.mkdirs(); String [] files = hyddTaizhang.getImg().split(","); //多个图片下载地址 for(int i=0;i<files.length;i++) { //new一个URL对象 URL url = new URL(files[i]); //打开链接 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置请求方式为"GET" conn.setRequestMethod("GET"); //超时响应时间为5秒 conn.setConnectTimeout(5 * 1000); //通过输入流获取图片数据 InputStream inStream = conn.getInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //创建一个Buffer字符串 byte[] buffer = new byte[1024]; //每次读取的字符串长度,如果为-1,代表全部读取完毕 int len = 0; //使用一个输入流从buffer里把数据读取出来 while( (len=inStream.read(buffer)) != -1 ){ //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 outStream.write(buffer, 0, len); } //关闭输入流 inStream.close(); //得到图片的二进制数据,以二进制封装得到数据,具有通用性 byte[] data = outStream.toByteArray(); //new一个文件对象用来保存图片,默认保存当前工程根目录 File imageFile = new File(src+"//"+hyddTaizhang.getXh()+"-"+i+".png"); //创建输出流 FileOutputStream outStreamres = new FileOutputStream(imageFile); //写入数据 outStreamres.write(data); //关闭输出流 outStreamres.close(); outStream.close(); } } //压缩文件夹 long start = System.currentTimeMillis(); FileOutputStream fos1 = new FileOutputStream(zipFilesrc); ZipOutputStream zos = null ; try { zos = new ZipOutputStream(fos1); File sourceFile = new File(filesrc); FileUtils.compress(sourceFile,zos,sourceFile.getName(),true); long end = System.currentTimeMillis(); log.info("压缩完成,耗时:" + (end - start) +" ms"); } catch (Exception e) { throw new RuntimeException("zip error from ZipUtils",e); }finally{ if(zos != null){ try { zos.close(); } catch (IOException e) { e.printStackTrace(); } } } //下载文件 File hardDiskFile = new File(zipFilesrc); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(hardDiskFile); } catch (FileNotFoundException e) { e.printStackTrace(); } InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); httpHeaders.setContentDispositionFormData("attachment", hardDiskFile.getName()); httpHeaders.setContentLength(hardDiskFile.length()); // 删除文件和压缩文件 FileUtils.delFolder(filesrc); return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.CREATED); }
工具类
package org.jeecg.modules.hydd.utils; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.FileInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @Slf4j public class FileUtils { /** * 递归压缩方法 * @param sourceFile 源文件 * @param zos zip输出流 * @param name 压缩后的名称 * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构; * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败) * @throws Exception */ public static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception{ byte[] buf = new byte[2 * 1024]; if(sourceFile.isFile()){ // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字 zos.putNextEntry(new ZipEntry(name)); // copy文件到zip输出流中 int len; FileInputStream in = new FileInputStream(sourceFile); while ((len = in.read(buf)) != -1){ zos.write(buf, 0, len); } // Complete the entry zos.closeEntry(); in.close(); } else { File[] listFiles = sourceFile.listFiles(); if(listFiles == null || listFiles.length == 0){ // 需要保留原来的文件结构时,需要对空文件夹进行处理 if(KeepDirStructure){ // 空文件夹的处理 zos.putNextEntry(new ZipEntry(name + "/")); // 没有文件,不需要文件的copy zos.closeEntry(); } }else { for (File file : listFiles) { // 判断是否需要保留原来的文件结构 if (KeepDirStructure) { // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠, // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了 compress(file, zos, name + "/" + file.getName(),KeepDirStructure); } else { compress(file, zos, file.getName(),KeepDirStructure); } } } } } /** * 删除文件夹 * @param folderPath 文件夹完整绝对路径 * @return */ public static void delFolder(String folderPath) { try { delAllFile(folderPath); //删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); //删除空文件夹 } catch (Exception e) { log.info("删除文件失败"); } } /** * 删除指定文件夹下所有文件 * @param path 文件夹完整绝对路径 * @return * @return */ public static boolean delAllFile(String path) { boolean bea = false; File file = new File(path); if (!file.exists()) { return bea; } if (!file.isDirectory()) { return bea; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); }else{ temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件 delFolder(path+"/"+ tempList[i]);//再删除空文件夹 bea = true; } } return bea; } }
Vue前端下载,定义全局方法
Vue.prototype.downBlobFlie = function(url, fileName, parameter) { var that = this this.$message.loading("下载中请不要关闭页面!",0) axios({ url: url, params: parameter, method: 'get', responseType: 'blob', onDownloadProgress: function(event) { // 下载进度监听 console.log(event) if (event.loaded === event.total) { // 下载完成 loading = true console.log("已完成"); that.$message.destroy() } } }).then((data) => { if (!data || data.size === 0) { Vue.prototype['$message'].warning('文件下载失败') return } if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(new Blob([data]), fileName) } else { let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', fileName) document.body.appendChild(link) link.click() document.body.removeChild(link) //下载完成移除元素 window.URL.revokeObjectURL(url) //释放掉blob对象 } }) }
- THE END -
最后修改:2022年8月1日