xml文件的生成和下载
生活随笔
收集整理的這篇文章主要介紹了
xml文件的生成和下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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));} elsereturn 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] ;}elsepathname += strs[i]+File.separator ;}return pathname;
}
?
?
//下載xml文件(壓縮包方式) public class DownloadXmlServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected 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 entryzos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if (listFiles == null || listFiles.length == 0) {// 需要保留原來的文件結構時,需要對空文件夾進行處理if (KeepDirStructure) {// 空文件夾的處理zos.putNextEntry(new ZipEntry(name + "/"));// 沒有文件,不需要文件的copyzos.closeEntry();}} else {for (File file : listFiles) {// 判斷是否需要保留原來的文件結構if (KeepDirStructure) {// 注意:file.getName()前面需要帶上父文件夾的名字加一斜杠,// 不然最后壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了compress(file, zos, name + "/" + file.getName(), KeepDirStructure);} else {compress(file, zos, file.getName(), KeepDirStructure);}}}}} }總結
以上是生活随笔為你收集整理的xml文件的生成和下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: YOLOv5/v7/v8首发原创改进《新
- 下一篇: Android Studio中两个模拟器