实现下载zip文件(含有模板生成的word)的几种方法

一.介绍

    本文使用了apache.tools 实现打包下载,并采用了两种不同的思路来实现。一种是在指定文件夹中生成临时文件,再将这些文件打包下载;另一种是直接将生成的文件直接写入zip的输出流。这里打包的文件有两个,一个是模板生成的word,另一个是  非结构化存储的文件(根据uuid获取)。下面是代码部分

二.

    第一种:

	public void exportQuaInfo() throws Exception{
		try {
			Map<String,Object> dataMap = new HashMap<String,Object>();
			dataMap = qualityManagementService.getDbInfoById(dbid);
			
			Configuration configuration = new Configuration();
			configuration = new Configuration();
			configuration.setDefaultEncoding("UTF-8");
			//加载需要装填的模板
			configuration.setClassForTemplateLoading(this.getClass(),"/com/njzaizao/web/secondRevision/qualityManagement");
			//设置对象包装器
			configuration.setObjectWrapper(new DefaultObjectWrapper());
			//设置异常处理器
			configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
			//定义Template对象
			Template template = configuration.getTemplate("dbk.ftl");
			
			//输出文档名字
			String fileName = "QC项目计划申报书.doc";
			String path = request.getSession().getServletContext().getRealPath("/tmp");  
			log.error(path);
			System.out.println(path);
			File saveDir = new File(path);
			if(!saveDir.exists()){
				saveDir.mkdirs();
			}
			File tmpOut = new File(path+"/"+fileName);//申报书临时文件的位置
			Writer out = null;
			FileOutputStream out2 = null;
			ZipOutputStream zos = null;
			FileInputStream fis = null;
			try {
				byte[] buffer = new byte[512];//定义缓冲区大小
				//将字符输出流包装为字节带缓冲区的输出流,并设置编码格式
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpOut),"UTF-8"));
				//将申报书按模板导出到指定文件夹
				template.process(dataMap, out);
				out.flush();
				out.close();
				if(StringUtil.availableStr(filePathXtly)){
					InputStream ins = FileRoboUtil.getInputStreamByUuid(filePathXtly);
					out2 = new FileOutputStream(path+"/"+"选题理由.doc");
					int byteRead = 0;
					
					while((byteRead = ins.read(buffer)) !=-1){
						out2.write(buffer,0,byteRead);
					}
					ins.close();
					out2.close();
					
				}
				
				String zipName = "QC项目计划申报书.zip";//压缩包的文件名
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;filename="
						+ new String(zipName.getBytes("GBK"), "ISO-8859-1"));
				response.setCharacterEncoding("utf-8");
				zos = new ZipOutputStream(response.getOutputStream());
				File sourceFile = new File(path);
				File[] sourceFiles = sourceFile.listFiles();//得到文件夹中所有临时文件
			
                               zos.setEncoding("GBK");//不加文件名乱码
for(int i =0;i<sourceFiles.length;i++){//创建ZIP实体,并添加进压缩包ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());zos.putNextEntry(zipEntry);
fis = new FileInputStream(sourceFiles[i]);//得到文件输入流IOUtils.copy(fis, zos);//将文件输入流复制到zip的输出流中fis.close();//关闭文件输入流zos.closeEntry();//关闭当前 ZIP 入口}zos.close();//遍历结束,关闭zip输出流Util.delAllFiles(path);//删除文件夹中临时文件}catch (Exception e) {e.printStackTrace(); } finally { }} catch (Exception e) {e.printStackTrace();}}    第二种:
public void exportSBCL() throws Exception{
		try {
			Map<String,Object> dataMap = new HashMap<String,Object>();
			String dwmcs = request.getParameter("dwmcs");
			String[] dwmcArr = dwmcs.split(",");
			String dbids = request.getParameter("dbids");
			String[] dbidsArr = dbids.split(",");
			String[] filePathXtlyArr = filePathXtly.split(",");
			String[] filePathHjArr = filePathHj.split(",");
			dataMap = qualityManagementService.getDbInfoById(dbidsArr[0]);
			
			Configuration configuration = new Configuration();
			configuration = new Configuration();
			configuration.setDefaultEncoding("UTF-8");
			//加载需要装填的模板
			configuration.setClassForTemplateLoading(this.getClass(),"/com/njzaizao/web/secondRevision/qualityManagement");
			//设置对象包装器
			configuration.setObjectWrapper(new DefaultObjectWrapper());
			//设置异常处理器
			configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
			//定义Template对象
			Template template = configuration.getTemplate("dbk.ftl");
			
			//输出文档名字
			String path = request.getSession().getServletContext().getRealPath("/tmp");
			log.error(path);
			System.out.println(path);
			ZipOutputStream zos = null;
			String zipName = dwmcArr[0]+"项目计划申请表.zip";//压缩包的文件名
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(zipName.getBytes("GBK"), "ISO-8859-1"));
			response.setCharacterEncoding("utf-8");
			zos = new ZipOutputStream(response.getOutputStream());
			zos.setEncoding("GBK");
			try {
				
				ZipEntry zipEntry = new ZipEntry(dwmcArr[0]+"项目计划申请表.doc");
				zos.putNextEntry(zipEntry);
				template.process(dataMap, new OutputStreamWriter(zos,"UTF-8"));
				zos.closeEntry();
				if(StringUtil.availableStr(filePathXtly)){
					InputStream ins = FileRoboUtil.getInputStreamByUuid(filePathXtlyArr[0]);
					ZipEntry zipEntry2 = new ZipEntry(dwmcArr[0]+"选题理由.doc");
					zos.putNextEntry(zipEntry2);
					IOUtils.copy(ins, zos);
					zos.closeEntry();//关闭当前 ZIP 入口
				}
				if(StringUtil.availableStr(filePathHj)){
					InputStream ins = FileRoboUtil.getInputStreamByUuid(filePathHjArr[0]);
					ZipEntry zipEntry2 = new ZipEntry(dwmcArr[0]+"获奖奖项.jpg");
					zos.putNextEntry(zipEntry2);
					IOUtils.copy(ins, zos);
					zos.closeEntry();//关闭当前 ZIP 入口
				}
				
				zos.close();//遍历结束,关闭zip输出流
				
			}catch (Exception e) {
				e.printStackTrace();
			 } finally {
				 
				}

			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

三.问题总结

    这两种方法在本机tomcat服务器下都没问题,但是在linux系统的 weblogic服务器运行时会出现文件乱码。这时使用ZipOutputStream 对象的setCoding方法,设置字符集为GBK。我查了下,window系统默认就是GBK,所以不设置也没事,Linux就不会默认GBK。而且这句话不能在设置每个压缩文件的时候都加入,也就是不能加多次。加了之后打开打包的word的时候,会报文件已损坏,根本打不开。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值