springboot实现单个文件的下载

      上篇博客讲解了通过springboot+easyui filebox实现文件的上传的功能,这次将实现通过springboot实现单个文件的下载功能。

      整个过程分为以下两步:

  1. 前台定义一个按钮,用于触发下载功能。
  2. 后台书写具体的文件下载代码

前台代码

HTML按钮代码如下

<td><a href="#button" class="button icon log" onclick="viewOnlineEvidence()">查看学习证明</a></td>

js代码如下:

function viewOnlineEvidence() {
        window.location.href="/downloadOnlineLearnMaterials";
    }

后台代码

@RequestMapping("/downloadOnlineLearnMaterials")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
   String fileName = "license_freeware.txt";// 设置文件名,根据业务需要替换成要下载的文件名
        if (fileName != null) {
            //设置文件路径
            String realPath = "E://onlineinfo//";
            File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    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);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
}

演示截图

这里写图片描述

前台按钮

这里写图片描述

文件夹信息

这里写图片描述

页面下载

springboot+easyui filebox文件上传博客链接如下,请多指教
http://blog.csdn.net/wilson_m/article/details/79175032

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值