web.xml文件的配置
<!--下载xml文件-->
<servlet>
<servlet-name>downloadXmlServlet</servlet-name>
<servlet-class>
com.zrp.uip.operator.controller.DownloadXmlServlet
</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>downloadXmlServlet</servlet-name>
<url-pattern>*.downloadxml</url-pattern>
</servlet-mapping>
excelProcess: function () {
var me = this;
var params = {};
略(ajax请求后台excelProcess的方法)
//下载xml文件
me.downloadXml("downloadXmlServlet.downloadxml","filename",me.currentNode.name);
},
/**
* 提交form 到servlet 下载xml文件
* @param action
* @param type
* @param value
*/
downloadXml:function(action, type, value){
var me = this;
var form = document.createElement('form');
document.body.appendChild(form);
form.style.display = "none";
form.action = action;
form.id = me.currentNode.id;
form.method = 'post';
var newElement = document.createElement("input");
newElement.setAttribute("type","hidden");
newElement.name = type;
newElement.value = value;
form.appendChild(newElement);
form.submit();
},
//生成xml文件(例:home/tomcat_test/webapps/UIPManager/WEB-INF)
public ServerResult<Boolean> excelProcess(@RequestBody Map map) throws Exception {
HttpServletRequest request = ContextUtil.getRequest();
Integer processID = Integer.valueOf(map.get("processID").toString());
ProcessSpecification specification = processSpecificationMapper.selectByPrimaryKey(processID);
String xmlname = specification.getProcessName();
//设置编码
request.setCharacterEncoding("UTF-8");
if (specification != null) {
Boolean flag = true;
//创建一个新文件夹
String oldPath = request.getSession().getServletContext().getRealPath("/xmlUpload");
String newPath = oldPath+File.separator + xmlname;
File file = new File(newPath);
file.mkdirs();
// 获取远程路径
String path = transformPath(newPath);
//生成Document对象 并生成XML文件
try {
// 生成路径
String processFilePath = path + File.separator +"xml.xml";
//生成Document元素对象
Document processDoc = exportProcessContentDoc(specification);
// 将document中的内容写入文件中
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
// 设置xml内容头部属性
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//编码格式
transformer.setOutputProperty(OutputKeys.INDENT, "yes");//格式化(缩进)
transformer.setOutputProperty(OutputKeys.STANDALONE, "no");//standalone=no 的属性设置
// 生成DOMSource对象 把流程内容写进对象里
DOMSource processFileSource = new DOMSource(processDoc);
StreamResult processFileResult = new StreamResult(new FileOutputStream(processFilePath));
transformer.transform(processFileSource, processFileResult);
System.out.println("xml文件生成成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("xml文件生成失败!");
flag = false;
}
if (flag) {
return new ServerResult<Boolean>(ResultCode.SUCCESS, "Judge repeated of project name verified success!",
new Boolean(true));
} else
return new ServerResult<Boolean>(ResultCode.FAILED, "Judge repeated of project name verified success!",
new Boolean(false));
} else {
return new ServerResult<Boolean>(ResultCode.FAILED, "Aims process didn't exists!", new Boolean(false));
}
}
//transformPath方法处理字符转义
private String transformPath(String path) {
//生成路径
String fileName = path ;
//处理字符串
String[] strs = fileName.split("\\\\");
String pathname = "";
for(int i =0;i<strs.length;i++){
if(i == strs.length-1){
pathname += strs[i] ;
}else
pathname += strs[i]+File.separator ;
}
return pathname;
}
//下载xml文件(压缩包方式)
public class DownloadXmlServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filename = req.getParameter("filename");
resp.reset();// 清空输出流
String resultFileName = filename + ".zip";//System.currentTimeMillis()
resultFileName = URLEncoder.encode(resultFileName, "UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
resp.setContentType("application/zip");// 定义输出类型
String path = req.getSession().getServletContext().getRealPath("/xmlUpload/"+filename);
//把文件压缩 后下载
ZipUtils.toZip(path, resp.getOutputStream(),false);
//删除 临时文件
delFolder(path);
}
/**
* 删除文件
* @param path
* @return
*/
public boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
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);// 再删除空文件夹
flag = true;
}
}
return flag;
}
/***
* 删除文件夹
* @param folderPath
*/
public void delFolder(String folderPath) {
try {
delAllFile(folderPath); // 删除完里面所有内容
String filePath = folderPath;
File myFilePath = new File(filePath);
myFilePath.delete(); // 删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @Author: youyang
* @Date: 2018/8/21 19:53
* @Description: ZipUtils工具类
*/
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
//ZIP压缩包工具类
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 压缩成ZIP 方法
* @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);
}
}
}
}
}
}