最近,本人需求将实现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文件所存在的位置
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"));
}
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();
}
}
}![]()
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.setContentType("application/x-download");
搞定 不懂可以咨询:本人QQ:3056643651


