一:思路
根据自己的需求,先将所需文件。下载到一个临时文件夹下,
再将整个文件夹进行压缩下载最后进行临时文件的删除。
二:开整
@Api(tags="xxx")
@RestController
@RequestMapping("/xxx/xxx")
@Slf4j
public class xxxController {
//这里我用了电脑根路径选作位临时文件位置 也可以放置在项目临时文件夹
//获取当前电脑根目录
private String gml = System.getProperties().getProperty("user.home");
/**
* 将文件打包成zip并下载
* //ZipUtils工具类
* //wttzListVo 我所需的查询数据可根据自己需求传参
*/
@PostMapping("/download")
@ApiOperation(value="列表导出", notes="质量导出")
public void download(HttpServletRequest request, HttpServletResponse response,WttzSearchVo wttzListVo) throws IOException {
//生成一个根目录加时间戳的路径
String path = gml + File.separator+"myfile";
ZipUtils.createfile(path);
//调取生成excle文件夹
this.myExcel(request,response,wttzListVo);
//生成相关文件包
this.xgwj(wttzListVo);
String zipName = "myfile.zip";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename="+zipName);
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
try {
ZipUtils.doCompress(path, out);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}finally{
//删除临时文件夹
File file = new File(path);
ZipUtils.deleteFile(file);
out.close();
}
}
//生成相关excle 这里我用的是jeecg(框架原因) 模板导出excle 需求可更具自己的来
public void myExcel(HttpServletRequest request, HttpServletResponse response,WttzSearchVo wttzListVo)
throws IOException {
Workbook workbook =fuza(wttzListVo);
File savefile = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath());
if (!savefile.exists()) {
savefile.mkdirs();
}
FileOutputStream fos = new FileOutputStream( gml + File.separator+"myfile/记录表.xls");
workbook.write(fos);
fos.close();
}
public TemplateExportParams getTemplateParams(){
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"templates/exporMyExcel.xls";
return new TemplateExportParams(path);
}
//生成相关excle文件
public Workbook fuza(WttzSearchVo wttzListVo) {
TemplateExportParams params = getTemplateParams();
Map<String, Object> map = new HashMap<String, Object>();
//导出数据查询
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
wttzListVo.setSysOrgCode(sysUser.getOrgCode());
Page<WttzListVo> page = new Page<WttzListVo>(1, Integer.MAX_VALUE);
List<WttzListVo> records = wtzgService.wttzList(page, wttzListVo).getRecords();
for (WttzListVo record:
records) {
//代码表转换
String wtzt = xgdmzh("app_zywt_wtzt", record.getWtzt());
record.setWtzt(wtzt);
String dqzt = xgdmzh("zljc_wttz_dqzt", record.getDqzt());
record.setDqzt(dqzt);
//字段更改
if(!StringUtils.isEmpty(record.getWtzp())&&!StringUtils.isEmpty(record.getZgzp())) {
record.setWtzp(record.getWtzp() + "/" + record.getZgzp());
}else if(!StringUtils.isEmpty(record.getWtzp())) {
record.setWtzp(record.getWtzp() + "/" + "0");
} else {
record.setWtzp("0");
}
String nameByCode = wtzgService.getNameByCode(record.getSysOrgCode());
record.setSysOrgCode(nameByCode);
}
map.put("maplist", records);
//jeecg boot 模板导出
Workbook workbook = ExcelExportUtil.exportExcel(params, map);
return workbook;
}
//生成相关文件
public void xgwj(WttzSearchVo wttzListVo){
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
wttzListVo.setSysOrgCode(sysUser.getOrgCode());
List<WttzdcList> records = wtzgService.getwjxx(wttzListVo);
for (WttzdcList record:
records) {
//问题照片
if(!StringUtils.isEmpty(record.getWtzp())) {
QueryWrapper<OSSFile> wrapper = new QueryWrapper<>();
String[] split = record.getWtzp().split(",");
wrapper.in("id", split);
//获取相关照片
List<OSSFile> list = ossFileService.list(wrapper);
for (OSSFile ossFile :
list) {
//遍历生成临时文件
ZipUtils.createfiles(gml + File.separator+"myfile/"+record.getWtbh(), ossFile);
}
}
//整改照片
if(!StringUtils.isEmpty(record.getZgzp())) {
QueryWrapper<OSSFile> wrapper = new QueryWrapper<>();
String[] split = record.getZgzp().split(",");
wrapper.in("id", split);
//获取相关照片
List<OSSFile> list = ossFileService.list(wrapper);
for (OSSFile ossFile :
list) {
//遍历生成临时文件
ZipUtils.createfiles(gml + File.separator+"myfile/"+record.getWtbh(), ossFile);
}
}
}
}
}
工具类
package org.jeecg.modules.zljc.util;
import org.jeecg.modules.oss.entity.OSSFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
private ZipUtils(){
}
public static void doCompress(String srcFile, String zipFile) throws IOException {
doCompress(new File(srcFile), new File(zipFile));
}
/**
* 文件压缩
* @param srcFile 目录或者单个文件
* @param zipFile 压缩后的ZIP文件
*/
public static void doCompress(File srcFile, File zipFile) throws IOException {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(zipFile));
doCompress(srcFile, out);
} catch (Exception e) {
throw e;
} finally {
out.close();//记得关闭资源
}
}
public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
doCompress(new File(filelName), out);
}
public static void doCompress(File file, ZipOutputStream out) throws IOException{
doCompress(file, out, "");
}
public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
if ( inFile.isDirectory() ) {
File[] files = inFile.listFiles();
if (files!=null && files.length>0) {
for (File file : files) {
String name = inFile.getName();
if (!"".equals(dir)) {
name = dir + "/" + name;
}
ZipUtils.doCompress(file, out, name);
}
}
} else {
ZipUtils.doZip(inFile, out, dir);
}
}
public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
String entryName = null;
if (!"".equals(dir)) {
entryName = dir + "/" + inFile.getName();
} else {
entryName = inFile.getName();
}
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
int len = 0 ;
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(inFile);
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
out.closeEntry();
fis.close();
}
public static void main(String[] args) throws IOException {
// String s = UUID.randomUUID().toString();
// String filepath = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"templates/compress/"+s;
//获取当前电脑根目录
String gml = System.getProperties().getProperty("user.home");
//生成一个根目录加时间戳的路径
String path = gml + File.separator+"111";
//doCompress(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"static/generic/build", "D:/java.zip");
}
//创建临时文件夹
public static void createfile(String filename){
File file =new File(filename);
//如果文件夹不存在则创建
if (!file.exists() && !file.isDirectory())
{
file.mkdirs();
}
}
//删除文件
public static void deleteFile(File file) {
if (file.exists()) {//判断文件是否存在
if (file.isFile()) {//判断是否是文件
file.delete();//删除文件
} else if (file.isDirectory()) {//否则如果它是一个目录
File[] files = file.listFiles();//声明目录下所有的文件 files[];
for (int i = 0;i < files.length;i ++) {//遍历目录下所有的文件
deleteFile(files[i]);//把每个文件用这个方法进行迭代
}
file.delete();//删除文件夹
}
} else {
System.out.println("所删除的文件不存在");
}
}
//将服务器文件下载至本地临时文件夹下
public static void createfiles(String filepath, OSSFile ossFile) {
HttpURLConnection conn = null;
InputStream inputStream = null;
BufferedInputStream bis = null;
FileOutputStream out = null;
try {
File file0 = new File(filepath);
if (!file0.isDirectory() && !file0.exists()) {
file0.mkdirs();
}
out = new FileOutputStream(file0 +"/"+ossFile.getFileName());
// 建立链接
URL httpUrl = new URL(ossFile.getUrl());
conn = (HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表单,默认get方式
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用缓存
conn.setUseCaches(false);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream = conn.getInputStream();
bis = new BufferedInputStream(inputStream);
byte b[] = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
out.write(b, 0, len);
}
System.out.println("下载完成...");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (bis != null) {
bis.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
主要是工具类 导出的可以根据自己的需求和实际情况来查询导出
。
测试
完美!成功。 初出茅庐,各位有好办法可以留言 ,学习一下!