java实现word下载及打包成zip下载(单个文件、多个文件)

最近,本人需求将实现word下载以及打包成zip进行下载(单个文件、多个文件)将最近自己学习到的知识点分享给大家

1.实现word模板(三个步骤,最终需要的是upload.ftl)

大家可以参考这篇文档https://www.cnblogs.com/Joanna-Yan/p/5280272.html


2.有些人地区需要对word文档进行加密,防止修改,但是如果设置为只读,是没有效果的。现在我告诉大家一种新的办法(在wps基础下)

打开新的word文档---------->点击工具-------->限制编辑-------->之后就自行操作


3.接下来就是根据模板进行下载word文档

1.获取模板路劲(自己定义)

      Configuration configuration = new Configuration();
      configuration.setDefaultEncoding("utf-8");
      configuration.setClassForTemplateLoading(this.getClass(),"/com/study/sta/template"); // FTL文件所存在的位置
2.map进行传值,放值
    for (Map<String, Object> inList : list) {
 String name = (String) inList.get("fullname");
map.put("fullname", inList.get("fullname"));
3.word下载
     t = configuration.getTemplate("upload5.ftl"); // 文件名
    File outFile = new File(path +"/"+ StrUtil.getString(map, "fullname")+idnumber +".docx");
   String path_msg = DateUtil.getDateyyyyMMdd();
   String filename = "报名表下载"+"/"+path_msg + "/"+ StrUtil.getString(map, "fullname") + StrUtil.getString(map, "idnumber")+"的报名表"+ ".docx";
   out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
   t.process(map, out);
   out.flush();
   String key = outFile.getCanonicalPath();
   InputStream content = new FileInputStream(key);
   ObjectMetadata meta = new ObjectMetadata();
   meta.setContentLength(key.length());
以上是针对一个word甚至多个word进行下载,
4.针对打包成zip形式传输到客户端下载(多个文件)
  本人的想法是在服务器端创建个文件夹,执行一次将这个文件夹里的文件删除
  • 先获取服务器存放word文档的路劲地址      
 String path = req.getRealPath("/upload");//create a path to save the file uploaded 
  • 再将改文件夹文件先删除(System.gc();    //回收资源,强制性删除,合理使用,因人而异。)
  File files = new File(path); 
if (!files.isDirectory()) {  
         files.delete();  
       } else if (files.isDirectory()) {  
        File[] fileList = files.listFiles();  
      for (int i = 0; i < fileList.length; i++) {  
        File delfile = fileList[i]; 
        int tryCount = 0;
  while ( tryCount++ < 10) {
        System.gc();    //回收资源
          delfile.delete(); 
      }
                        
  }  
   }      
  • 最后即可压缩
  resp.addHeader("Content-Disposition", "attachment;filename="+ DateUtil.getDateyyyyMMddHHmmss() + "cert.zip");
  resp.setContentType("application/x-download");
搞定  不懂可以咨询:本人QQ:3056643651微笑微笑
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值