学习内容:
需求是批量导出带图片
注意
想要使用需要获取地址方法ConfigManager.getAttatchmentsPath(),这个方法是我自己项目里的默认地址
学习产出:
首先需要从数据库中提取clob,转换成string型
提供工具方法
public String ClobToString(Clob clob){
String reString = "";
try {
Reader is = clob.getCharacterStream();// 得到流
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
sb.append(s);
s = br.readLine();
}
reString = sb.toString();
} catch (Exception e) {
// TODO: handle exception
log.error(e,e);
}
return reString;
}
注意需要符号转换,word不能直接识别标签
生成过程中需要压缩文件夹所有
压缩文件工具类
package com.hyjx.business_xhzb.trts;
import org.apache.log4j.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 将文件夹下面的文件 打包成zip压缩文件
*
* @author admin
*
*/
public final class FileToZip {
private static Logger log = Logger.getLogger(FileToZip.class);
public static String compressToZip(String sourceFilePath, String zipFilePath, String zipFilename) {
File sourceFile = new File(sourceFilePath);
File zipPath = new File(zipFilePath);
if (!zipPath.exists()) {
zipPath.mkdirs();
}
File zipFile = new File(zipPath + File.separator + zipFilename);
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
writeZip(sourceFile, "", zos);
//文件压缩完成后,删除被压缩文件
deleteDir(sourceFile);
} catch (Exception e) {
log.error(e,e);
throw new RuntimeException(e.getMessage(), e.getCause());
}
return zipPath + File.separator + zipFilename;
}
/**
* 删除文件夹
*
* @param dir
* @return
*/
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
//删除空文件夹
return dir.delete();
}
/**
* 遍历所有文件,压缩
*
* @param file 源文件目录
* @param parentPath 压缩文件目录
* @param zos 文件流
*/
public static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.isDirectory()) {
//目录
parentPath += file.getName() + File.separator;
File[] files = file.listFiles();
for (File f : files) {
writeZip(f, parentPath, zos);
}
} else {
//文件
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
//指定zip文件夹
ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(zipEntry);
int len;
byte[] buffer = new byte[1024 * 10];
while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
zos.write(buffer, 0, len);
zos.flush();
}
} catch (Exception e) {
log.error(e,e);
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
}
private FileToZip() {
}
/**
* 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
*
* @param sourceFilePath
* :待压缩的文件路径
* @param zipFilePath
* :压缩后存放路径
* @param fileName
* :压缩后文件的名称
* @return
*/
public static String fileToZip(String sourceFilePath, String zipFilePath,
String fileName) {
String zipPath = null;
File sourceFile = new File(sourceFilePath);
FileOutputStream fos = null;
ZipOutputStream zos = null;
FileInputStream fis = null;
//BufferedInputStream bis = null;
List<BufferedInputStream> bisList = new ArrayList<>();
try{
zipPath = zipFilePath + File.separator + fileName + ".zip";
if (sourceFile.exists() == false) {
log.info("待压缩的文件目录:" + sourceFilePath + "不存在.");
} else {
File zipFile = new File(zipPath);
if (zipFile.exists()) {
log.info(zipFilePath + "目录下存在名字为:" + fileName
+ ".zip" + "打包文件.");
} else {
File[] sourceFiles = sourceFile.listFiles();
if (null == sourceFiles || sourceFiles.length < 1) {
log.info("待压缩的文件目录:" + sourceFilePath
+ "里面不存在文件,无需压缩.");
} else {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024 * 10];
for (int i = 0; i < sourceFiles.length; i++) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(
sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
BufferedInputStream bis = new BufferedInputStream(fis, 1024 * 10);
bisList.add(bis);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
}
}
}
}
}catch (Exception e){
log.error(e,e);
}finally {
if(bisList != null && bisList.size()>0){
for (BufferedInputStream bisitem:bisList) {
try {
bisitem.close();
} catch (IOException e) {
log.error(e,e);
}
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
log.error(e,e);
}
}
if(zos != null){
try {
zos.close();
} catch (IOException e) {
log.error(e,e);
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
log.error(e,e);
}
}
}
return zipPath;
}
}
本地图片转换base64方法,用来写入图片
/**
* 本地图片转换Base64的方法
*
* @param imgPath
*/
private static String ImageToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
log.error(e,e);
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
System.out.println("本地图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
return encoder.encode(Objects.requireNonNull(data));
}
获取img标签内容方法
public void getImgStr(String htmlStr ,List<String> pics) {
String img = "";
Pattern p_image;
Matcher m_image;
// String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(htmlStr);
while (m_image.find()) {
// 得到<img />数据
img = m_image.group();
getImgStr1(img);
// 匹配<img>中的src数据
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
pics.add(m.group(1));
}
}
System.out.println(pics);
}
public void getImgStr1(String htmlStr) {
String[] pics = htmlStr.split(" ");
for (String pic : pics) {
if (pic.contains("src")) {
String src = pic;
String substring = src.substring(5, src.length() - 1);
System.out.println(substring);
}
}
}
生成文件压缩zip
public String wordout(String ids) throws Exception {
try {
/***
* 生成文件夹
*/
String fristPath = ConfigManager.getAttatchmentsPath()+"bgsnotice"+File.separator+ "信息发布内容";
System.out.println(fristPath);
if(!new File(fristPath).exists()){
new File(fristPath).mkdirs();
}
String[] id=ids.split(",");
/*
* 遍历id,生成对应word
* */
for (String nid:id) {
List<String> pics = new ArrayList<>();
Map<String,String> kv=new HashMap<>();
BgsnoticeModel model=service.getInfoById(nid);
String val=model.getInfovalue();
if(StringUtils.isNotBlank(val)){
val = val.replace("<","<").replace(">",">");//替换符号
getImgStr(val, pics);//通过正则提取img片段
}
int i=0;
for (String ls: pics) {
try{
val=val.replace("<img src=\""+ls+"\" alt=\"\" />","<img src=\"pic"+i+"\" alt=\"\" width=\"300\" height=\"300\"/>");//替换默认标签,给与默认宽度
String[] ac= ls.split("=");//找到文件地址src
ls=ac[1];
kv.put("pic"+i+"",ls);//
i++;}catch (Exception e)
{log.error(e,e);
continue;}
}
String content="Mime-Version: 1.0\n" +
"Content-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n" +
"\n" +
"--NEXT.ITEM-BOUNDARY\n" +
"Content-Type: text/html; charset=\"utf-8\"\n"+
"\n";//必须要这个格式,才能识别base64代码
content +="<html>"+"<div style=\"text-align: center\"><span style=\"font-size: 24px\"><span style=\"font-family: 黑体\">"+model.getTitle()+"<br /> <br /> </span></span></div>"+val+"</html>\n";
for (i=0;i<kv.size();i++) {
try {
String c=kv.get("pic"+i+"");
String imgstr = ImageToBase64(ConfigManager.getAttatchmentsPath()+"bgsnotice"+File.separator+c);
content+="--NEXT.ITEM-BOUNDARY\n" +
"Content-Location: pic"+i+"\n" +
"Content-Type: image/png\n" +
"Content-Transfer-Encoding: base64\n" +
"\n" +
imgstr+"\n"+
"\n";}
catch (Exception e){
log.error(e,e);
continue;
}
}
content+="--NEXT.ITEM-BOUNDARY--";
byte b[] = content.getBytes();
String secondPath =fristPath+File.separator+model.getTitle()+".doc";
FileOutputStream bendi = new FileOutputStream(secondPath);
bendi.write(b);
bendi.close();
}
//生成压缩文件删除原有文件
return FileToZip.compressToZip(fristPath,ConfigManager.getAttatchmentsPath()+"bgsnoticezip","信息发布内容"+ StringHelper.getPrimaryKey().substring(1,5)+".zip");
} catch (IOException e) {
log.error(e,e);
}
return null;
}
controller输出zip文件
@RequestMapping(value = "/downword",produces = "application/json; charset=utf-8", method = {RequestMethod.POST,RequestMethod.GET})
public String downword(HttpServletRequest request, HttpServletResponse response) throws Exception {
String ids= request.getParameter("ids");
FileInputStream in = null;
java.io.OutputStream out = null;
try {
String filePath = wordout(ids);
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-disposition", "attachment;filename="
+ java.net.URLEncoder.encode("信息发布内容.zip", "utf-8"));
in = new FileInputStream(filePath);
out = response.getOutputStream();
int len = 0;
byte buf[] = new byte[1024];// 缓存作用
while ((len = in.read(buf)) > 0) // 切忌这后面不能加 分号 ”;“
{
out.write(buf, 0, len);// 向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取
}
out.flush();
} catch (Exception e) {
log.error(e,e);
}finally {
if(out != null){
try {
out.close();
} catch (IOException e) {
log.error(e,e);
}
}
if(in != null){
try {
in.close();
} catch (IOException e) {
log.error(e,e);
}
}
}
return null;
}