随笔 - 434,  文章 - 0,  评论 - 463,  阅读 - 46万

这一节的目的是实现文件的打包下载。
有了Hutool,感觉轻松多了呢!
我们还是要导入Hutool,帮我们省去文件操作的麻烦。

修改页面

image

<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();
}

因为本项目非常简单,如果感兴趣地话,个人建议大家自己动手练一练。(毕竟也没多少行代码)

所以,这边就不提供完整项目了。

image

比如我点击第二个打包下载。

image

就真的下载下来了。

image

而且,压缩包是自动删掉的。

posted on   剽悍一小兔  阅读(32)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示