绘制多个word表格,压缩文件夹并输出流

1.添加依赖

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
=========================================================================================
=========================================================================================

2.控制层代码


import cn.hsa.ext.base.ConfigContants;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hsa.powersi.eldly.manmanage.dto.AssessReportDTO;

import cn.hsa.powersi.eldly.manmanage.dto.BsAssessDTO;
import cn.hsa.powersi.eldly.manmanage.service.AssessReportService;
import cn.hsa.powersi.eldly.util.PdfUtil;
import cn.hsa.powersi.eldly.util.ZipUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@PostMapping("/exportAssessReport")
@ApiOperation(value = "导出评估报告")
public void exportAssessReport(@RequestBody @ApiParam(name = "评估报告对象", value = "传入json格式", required = true)
AssessReportDTO assessReportDTO, HttpServletResponse response, HttpServletRequest request) {
List<AssessReportDTO> assessReportDTOS = assessReportService.findAssessReportDetail(assessReportDTO);
AssessReportDTO assessReportDTO1=assessReportDTOS.get(0);
//本地文件路径 uri=file:/F:/zhyl-idea/eldly-base/eldly-generic/target/classes/
java.net.URL uri = this.getClass().getResource("/");
String foldpath=ConfigContants.LOCAL_ZIP_PATH;
try {
// 1.新建document对象
Document document = new Document(PageSize.A4);// 建立一个Document对象
// 2.建立一个书写器(Writer)与document对象关联

String filePath=uri.toString().substring(6)+foldpath;
String fileName = "评估汇总报告.pdf";
// 在内存中创建一个文件对象,注意:此时还没有在硬盘对应目录下创建实实在在的文件
String allpath=filePath;
allpath = allpath.replace("/","\\\\");
File f = new File(allpath+fileName);
if(!f.exists()) {
// 先创建文件所在的目录
f.getParentFile().mkdirs();
f.createNewFile();
}

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
// 3.打开文档
document.open();


// 4.向文档中添加内容
new PdfUtil().generatePDF(document,assessReportDTO1);
// 5.关闭文档
document.close();
List<BsAssessDTO> assessinfos = assessReportDTO1.getAssessinfos();
for(BsAssessDTO bsAssessDTO:assessinfos){
List<BsAssessDTO> assessRecordDetail = assessReportService.findAssessRecordDetail(bsAssessDTO);
BsAssessDTO bsAssessDTO1 = assessRecordDetail.get(0);
bsAssessDTO1.setTemplateName(bsAssessDTO.getTemplateName());
String fileName1 = bsAssessDTO.getTemplateName()+".pdf";
// 在内存中创建一个文件对象,注意:此时还没有在硬盘对应目录下创建实实在在的文件
File f2 = new File(allpath+fileName1);
if(!f2.exists()) {
// 先创建文件所在的目录
f2.getParentFile().mkdirs();
}
f2.createNewFile();

Document document2 = new Document(PageSize.A4);// 建立一个Document对象

PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(f2));
// 3.打开文档
document2.open();
// 4.向文档中添加内容
new PdfUtil().generateReportPDF(document2,assessReportDTO1,bsAssessDTO1);
document2.close();
}


ZipOutputStream zos = null;
File inputFile = new File(allpath);
if(inputFile != null && inputFile.exists()) {
try {

//第二个参数为:要压缩文件的地址
ZipUtil.exportZip(response, allpath,"评估报告");



}catch(Exception e) {
System.out.println("文件压缩异常:" + e);
throw e;
}finally {
try {
if(zos != null) {
//先调用outputStream的flush()再关闭流;
//流如果未正常关闭,则会在解压的时候出现压缩文件损坏的现象
zos.flush();
zos.close();
}

//递归删除源文件及源文件夹
File inputFile1 = new File(allpath);
ZipUtil.deleteFile(inputFile1);

}catch(Exception ex) {
System.out.println("输出流关闭异常:" + ex);
}
}
}



} catch (Exception e) {
e.printStackTrace();
}


}
=========================================================================================
=========================================================================================
3.pdf工具栏代码

package cn.hsa.powersi.eldly.util;

import cn.hsa.powersi.eldly.manmanage.dto.AssessReportDTO;
import cn.hsa.powersi.eldly.manmanage.dto.BsAssessDTO;
import cn.hsa.powersi.eldly.manmanage.dto.BsAssessRecordDTO;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;


import java.io.File;
import java.io.FileOutputStream;

import java.util.List;

/**
* @author xiejun
* @title: PdfUtil
* @projectName powersi-eldly-cloud
* @description: TODO
* @date 2022/2/23 14:47
*/
public class PdfUtil {

// main测试
public static void main(String[] args) throws Exception {
try {
// 1.新建document对象
Document document = new Document(PageSize.A4);// 建立一个Document对象

// 2.建立一个书写器(Writer)与document对象关联
File file = new File("D:\\PDFDemo.pdf");
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

// 3.打开文档
document.open();
document.addTitle("Title@PDF-Java");// 标题
document.addAuthor("Author@umiz");// 作者
document.addSubject("Subject@iText pdf sample");// 主题
document.addKeywords("Keywords@iTextpdf");// 关键字
document.addCreator("Creator@umiz`s");// 创建者

// 4.向文档中添加内容
// new PdfUtil().generatePDF(document);

// 5.关闭文档
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}

// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
// 最大宽度
private static int maxWidth = 520;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.BOLD);
headfont = new Font(bfChinese, 12, Font.BOLD);
keyfont = new Font(bfChinese, 10, Font.BOLD);
textfont = new Font(bfChinese, 10, Font.NORMAL);

} catch (Exception e) {
e.printStackTrace();
}
}

// 生成汇总评估报告PDF文件
public void generatePDF(Document document, AssessReportDTO assessReportDTO) throws Exception {

// 段落
Paragraph paragraph = new Paragraph("评估报告", titlefont);
paragraph.setAlignment(1); //设置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //设置左缩进
paragraph.setIndentationRight(12); //设置右缩进
paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(20f); //行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白



// 基本信息表格
PdfPTable table = createTable(new float[] { 60, 140, 60, 140, 60, 140 });
table.addCell(createCell("一、基本信息", headfont, Element.ALIGN_LEFT, 6));

table.addCell(createCell("老人姓名", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getName(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("性别", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getSexStr(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("年龄", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getAge(), textfont, Element.ALIGN_CENTER));

table.addCell(createCell("联系电话", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getPhone(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("入住时间", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getCheckinTimeStr(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("床位号", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getBedName(), textfont, Element.ALIGN_CENTER));

table.addCell(createCell("评估时间", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getReportTimeName(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("评估结果", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getGradingName(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("评估员", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getAssessName(), textfont, Element.ALIGN_CENTER));

table.addCell(createCell("评估备注", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getAssessNote(), textfont, Element.ALIGN_CENTER, 5));

// 评估内容表格
PdfPTable contentTable = createTable(new float[] { 40, 230, 50, 230 });
contentTable.addCell(createCell("二、评估内容", headfont, Element.ALIGN_LEFT, 4));

contentTable.addCell(createCell("序号", keyfont));
contentTable.addCell(createCell("评估内容", keyfont));
contentTable.addCell(createCell("评估得分", keyfont));
contentTable.addCell(createCell("评估结果", keyfont));
List<BsAssessDTO> assessinfos = assessReportDTO.getAssessinfos();
if(assessinfos!=null&&assessinfos.size()>0){
for (int i = 0; i <assessinfos.size(); i++) {
contentTable.addCell(createCell(i+1+"", textfont));
contentTable.addCell(createCell(assessinfos.get(i).getTemplateName(), textfont));
contentTable.addCell(createCell(assessinfos.get(i).getScore(), textfont));
contentTable.addCell(createCell(assessinfos.get(i).getAssessResult(), textfont));
}
}



document.add(paragraph);

document.add(table);
document.add(contentTable);
}



// 生成汇总评估报告PDF文件
public void generateReportPDF(Document document, AssessReportDTO assessReportDTO, BsAssessDTO bsAssessDTO) throws Exception {

// 段落
Paragraph paragraph = new Paragraph(bsAssessDTO.getTemplateName(), titlefont);
paragraph.setAlignment(1); //设置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //设置左缩进
paragraph.setIndentationRight(12); //设置右缩进
paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(20f); //行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白



// 基本信息表格
PdfPTable table = createTable(new float[] { 60, 140, 60, 140, 60, 140 });
table.addCell(createCell("一、基本信息", headfont, Element.ALIGN_LEFT, 6));

table.addCell(createCell("老人姓名", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getName(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("性别", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getSexStr(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("年龄", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getAge(), textfont, Element.ALIGN_CENTER));

table.addCell(createCell("联系电话", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getPhone(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("入住时间", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getCheckinTimeStr(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("床位号", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getBedName(), textfont, Element.ALIGN_CENTER));

table.addCell(createCell("评估时间", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getReportTimeName(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("评估结果", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getGradingName(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell("评估员", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getAssessName(), textfont, Element.ALIGN_CENTER));

table.addCell(createCell("评估备注", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell(assessReportDTO.getAssessNote(), textfont, Element.ALIGN_CENTER, 5));

// 评估内容表格
PdfPTable contentTable = createTable(new float[] { 40, 230, 50, 230 });
contentTable.addCell(createCell("二、评估内容", headfont, Element.ALIGN_LEFT, 4));

contentTable.addCell(createCell("序号", keyfont));
contentTable.addCell(createCell("题目", keyfont));
contentTable.addCell(createCell("可选项", keyfont));
contentTable.addCell(createCell("选择项", keyfont));
contentTable.addCell(createCell("得分", keyfont));
List<BsAssessRecordDTO> assessRecords = bsAssessDTO.getAssessRecords();
if(assessRecords!=null&&assessRecords.size()>0){
for (int i = 0; i <assessRecords.size(); i++) {
contentTable.addCell(createCell(i+1+"", textfont));
contentTable.addCell(createCell(assessRecords.get(i).getQuestionDesc(), textfont));
contentTable.addCell(createCell(assessRecords.get(i).getOptions(), textfont));
contentTable.addCell(createCell(assessRecords.get(i).getChooseOption(), textfont));
contentTable.addCell(createCell(assessRecords.get(i).getScore(), textfont));

}
}



document.add(paragraph);

document.add(table);
document.add(contentTable);
}


/**------------------------创建表格单元格的方法start----------------------------*/
/**
* 创建单元格(指定字体)
* @param value
* @param font
* @return
*/
public PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平..)
* @param value
* @param font
* @param align
* @return
*/
public PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并)
* @param value
* @param font
* @param align
* @param colspan
* @return
*/
public PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
* @param value
* @param font
* @param align
* @param colspan
* @param boderFlag
* @return
*/
public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(15.0f);
cell.setPaddingBottom(8.0f);
} else if (boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(15.0f);
}
return cell;
}
/**
* 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
* @param value
* @param font
* @param align
* @param borderWidth
* @param paddingSize
* @param flag
* @return
*/
public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setBorderWidthLeft(borderWidth[0]);
cell.setBorderWidthRight(borderWidth[1]);
cell.setBorderWidthTop(borderWidth[2]);
cell.setBorderWidthBottom(borderWidth[3]);
cell.setPaddingTop(paddingSize[0]);
cell.setPaddingBottom(paddingSize[1]);
if (flag) {
cell.setColspan(2);
}
return cell;
}
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start------------------- ---------*/
/**
* 创建默认列宽,指定列数、水平(居中、右、左)的表格
* @param colNumber
* @param align
* @return
*/
public PdfPTable createTable(int colNumber, int align) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(align);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建指定列宽、列数的表格
* @param widths
* @return
*/
public PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建空白的表格
* @return
*/
public PdfPTable createBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyfont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
/**--------------------------创建表格的方法end------------------- ---------*/


}
=========================================================================================
=========================================================================================
=========================================================================================
=========================================================================================
4.ziputil工具类代码
package cn.hsa.powersi.eldly.util;


import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* @author xiejun
* @title: PdfUtil
* @projectName powersi-eldly-cloud
* @description: TODO
* @date 2022/2/23 14:47
*/
public class ZipUtil {

private static final int BUFFER_SIZE = 2 * 1024;

public static final String FILE_SEPARATOR = System.getProperty("file.separator", "\\");




/**
* 递归删除文件夹中的目录及文件
*
* @param sourceFile
* @throws Exception
*/
public static void deleteFile(File sourceFile) throws Exception{
//如果路径为目录
if(sourceFile.isDirectory()) {
//取出文件夹中的文件或子文件夹
File[] fList = sourceFile.listFiles();
if(fList.length == 0) {
sourceFile.delete();
}else {
for(int i = 0; i < fList.length; i++) {
deleteFile(fList[i]);
}
sourceFile.delete();
}
//如果为文件则直接删除
}else {
sourceFile.delete();
}
}

/**
* 压缩成ZIP 方法1
* @param srcDir 压缩文件夹路径
* @param out 压缩文件输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{

long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (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();
}
}
}

}

/**
* 递归压缩方法
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
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);
}

}
}
}
}









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);
handlerFile(zip, file,"");
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}


public static void exportZip(HttpServletResponse response, String sourceFilePath,String downloadName) {

//将文件进行打包下载
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''" + URLEncoder.encode(downloadName, "utf-8")+".zip");
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();
}
}



}


posted @ 2022-02-28 14:24  萧长风  阅读(167)  评论(0编辑  收藏  举报