JAVA打包xml成zip保存在服务器任意位置,并能在页面进行点击下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lixin2151408/article/details/71713712

这几天做了个前台点击查询后,将后台查询的xml进行打包,形成zip(可存在服务器任意位置),并在前台页面可以点击下载进行下载:


打包代码:

public String savexml(List<Map> list) throws IOException{
		int i;
		Calendar c = Calendar.getInstance();
    	String year = c.get(Calendar.YEAR)+"";
    	String month = c.get(Calendar.MONTH)+1+""; 
    	String date = c.get(Calendar.DATE)+""; 
    	String hour = c.get(Calendar.HOUR_OF_DAY)+""; 
    	String minute = c.get(Calendar.MINUTE)+""; 
    	String second = c.get(Calendar.SECOND)+"";
    	String data = year+month+date+hour+minute+second;
    	//首先生成一个文件夹,存放此次查询获得的xml;
    	String path = this.getClass().getResource("/").getPath();
    	System.err.println(path);
    	
    	File file = new File("F:\\xml\\"+data+"");
    	file.mkdirs();
		String filename = null;
		String xmlcontent = null;
		//将查询获得的xml依次存放入此文件夹中;
		Map map = new HashMap();
		for(i=0;i<list.size();i++){
			map = list.get(i);
//			System.err.println(map);
			if(map.get("FILENAME")!=null){filename=map.get("FILENAME").toString();}
			if(map.get("XMLCONTENT")!=null){xmlcontent=map.get("XMLCONTENT").toString();}
			FileWriter fw = new FileWriter("F:\\xml\\"+data+"\\"+filename+"");
//			System.out.println("~~~~~~~"+xmlcontent);
			fw.write(xmlcontent);
			fw.flush();
			fw.close();
		}
		 String sourceFilePath = "F:\\xml\\"+data+"";  
	        String zipFilePath = "F:\\xml\\"+data+"";  
	        String fileName = data;
		boolean flag = fileToZip(sourceFilePath, zipFilePath, fileName);  
        if(flag){  
            System.out.println("文件打包成功!");  
        }else{  
            System.out.println("文件打包失败!");  
        }
        return zipFilePath+"\\"+fileName;
	}
	
	/** 
     * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下 
     * @param sourceFilePath :待压缩的文件路径 
     * @param zipFilePath :压缩后存放路径 
     * @param fileName :压缩后文件的名称 
     * @return 
     */  
    public static boolean fileToZip(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() == false){  
            System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");  
        }else{  
            try {  
                File zipFile = new File(zipFilePath + "/" + fileName +".zip");  
                if(zipFile.exists()){  
                    System.out.println(zipFilePath + "目录下存在名字为:" + 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());  
                            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();  
                throw new RuntimeException(e);  
            } catch (IOException e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            } finally{  
                //关闭流  
                try {  
                    if(null != bis) bis.close();  
                    if(null != zos) zos.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    throw new RuntimeException(e);  
                }  
            }  
        }  
        return flag;  
    }  

下载代码:controller:

@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public void exportZip(HttpServletRequest request, HttpServletResponse response) {
		String path = request.getQueryString();
		path = path.substring(5);
		path = path.replaceAll(";", "\\\\");
	    File file = new File(path);// path是根据日志路径和文件名拼接出来的
	    String filename = file.getName();// 获取日志文件名称
	    response.setCharacterEncoding("utf-8");
	    response.setContentType("multipart/form-data");
	    response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
	    try {
	        //打开本地文件流
	        InputStream inputStream = new FileInputStream(path);
	        //激活下载操作
	        OutputStream os = response.getOutputStream();

	        //循环写入输出流
	        byte[] b = new byte[2048];
	        int length;
	        while ((length = inputStream.read(b)) > 0) {
	            os.write(b, 0, length);
	        }

	        // 这里主要关闭。
	        os.close();
	        inputStream.close();
	    } catch (Exception e){
	    	e.printStackTrace();
	    }
	}

前台页面JS:

function query()
		{
			var areacode=$('#areacode').textbox('getValue');
			var rectype=$('#rectype').textbox('getValue');
			var filename=$('#filename').textbox('getValue');
			var bdcdyh=$('#bdcdyh').textbox('getValue');
			var kjjd=$("#kjjd").is(":checked");
			var page = $("#mylist").datagrid("options").pageNumber;
			var rows = $("#mylist").datagrid("options").pageSize;
			var status = $("#status option:selected").attr("value");
			para = { page : page, rows : rows, areacode : areacode, rectype : rectype, filename : filename, bdcdyh : bdcdyh, kjjd : kjjd , status : status};
			$("#mylist").datagrid({
				url : "../common/loglist/",
				method : 'get',
				queryParams : para,
				rownumbers : true,
				fitColumns : true,
				pagination : true,
				pageSize:100,
				 height:screen.availHeight-155,
				pageList : [ 100, 150, 200, 400, 500 ],
				onLoadSuccess:function(data){
					data.urls = data.urls+".zip";
					var path = data.urls.replace(/\\/g,';');
					$("#export").attr("href","../common/upload?path="+path)
				}
			});
		}

有几点需要注意:

①我是将文件位置传给了后台,但是文件名是:F:/XXX/XX.zip;但是浏览器会将/字符当成转义字符,在这里卡住了好久才明白哪里错了。于是我在前台将 / 替换成了;然后再传给后台;

②后台一定要写response属性啊:

    response.setCharacterEncoding("utf-8");
   response.setContentType("multipart/form-data");
   response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

这三句话如果不加上,浏览器会出现自行编译,可能会出现前台response错误;

③下载的时候,直接a标签链接服务器接口地址!

猜你喜欢

转载自blog.csdn.net/lixin2151408/article/details/71713712