这一节的目的是实现文件的打包下载。
有了Hutool,感觉轻松多了呢!
我们还是要导入Hutool,帮我们省去文件操作的麻烦。
修改页面
<ul>
<li th:each="file:${files}">
[[${file.getName()}]]
<a th:href="@{'download?file='+${file.getName()}}">
打包下载
</a>
</li>
</ul>
和之前不同,这边不用th:text了,然后在每个文件旁边加一个打包下载的超链接。
在IndexController中添加一个新的方法
@RequestMapping("/download")
@ResponseBody
public void index(String file){
String targetName = diskpath + File.separator + file;
//打包到当前目录
ZipUtil.zip(targetName);
}
ZipUtil是Hutool提供的,我们直接拿来用即可。
重新写download方法,增加下载功能
@RequestMapping("/download")
@ResponseBody
public void download(String file, HttpServletResponse response) throws UnsupportedEncodingException, FileNotFoundException {
String targetName = diskpath + File.separator + file;
//打包到当前目录
ZipUtil.zip(targetName);
targetName = targetName+".zip";
response.setContentType("application/force-download");
//解决下载文件名中文不显示的问题
String fileName = new String(file.getBytes("utf-8"),"ISO8859-1");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName + ".zip");
//输出流,下载文件
byte[] buffer = new byte[1024];
try {
FileInputStream fis = new FileInputStream(targetName);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
如何下载完毕后就删掉zip文件
很简单,在下载完毕后,立刻调用删除的方法即可。注意,删文件之前,一定要关闭流!
核心代码如下:
//输出流,下载文件
byte[] buffer = new byte[1024];
try {
FileInputStream fis = new FileInputStream(targetName);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
//关闭流
fis.close();
os.close();
boolean del = FileUtil.del(targetName);
System.out.println(del);
} catch (IOException e) {
e.printStackTrace();
}
因为本项目非常简单,如果感兴趣地话,个人建议大家自己动手练一练。(毕竟也没多少行代码)
所以,这边就不提供完整项目了。
比如我点击第二个打包下载。
就真的下载下来了。
而且,压缩包是自动删掉的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)