java freemarker 根据xml模板生成word,浏览器下载产生多余的代码问题

问题描述:不管是wps生成的xml模板还是office生成的xml模板,下载的时候都会追加多余的代码,导致office打开有问题如图

找了很久,终于发现和生成的word没啥关系,和浏览器下载的时候回追加一段代码如:

这个是wps生成的xml模板,office也是同样。

解决问题思路:既然和生成word的没啥关系,和浏览器下载的时候有关系。那就对该文件进行压缩,在下载,说干就干。利用java提供的压缩方法。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
* 压缩文件工具类
* @author jhsz15
*
*/
@Service
public class FileToZip {
private static final Logger LOGGER = LoggerFactory.getLogger(FileToZip.class);
/**
* 压缩方法
* @param sourceFilePath 源文件夹路径
* @param zipFilePath 压缩文件夹路径
* @param fileName 文件名称
* @return
*/
public boolean tozip(String sourceFilePath,String zipFilePath,String fileName) {
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if(!sourceFile.exists()) {
System.out.println(sourceFilePath+"没有需要压缩的文件!");
}else {
try {
File zipFile = new File(zipFilePath+"/"+fileName+".zip");
if(zipFile.exists()) {
System.out.println(sourceFilePath+"已经存在"+fileName+".zip");
}else {
File[] sourceFiles = sourceFile.listFiles();
if(null == sourceFiles || sourceFiles.length<1) {
System.out.println(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());
System.out.println(zipEntry);
zos.putNextEntry(zipEntry);
//读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis,1024*10);
int read = 0;
while((read = bis.read(bufs,0,1024*10))!=-1) {
zos.write(bufs,0,read);
}
}
flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
LOGGER.error("压缩文件异常:"+e.getMessage());
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("压缩文件异常:"+e.getMessage());
throw new RuntimeException(e);
}finally {
try {
if(null != bis) {
bis.close();
}
if(null != zos) {
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("压缩文件异常:"+e.getMessage());
throw new RuntimeException(e);
}
}
}
return flag;
}
}
然后在下载,果然解决了问题。

猜你喜欢

转载自blog.csdn.net/joe192/article/details/80418799
今日推荐