Java文件的下载

本片文章为Java文件下载,仅做以后用到是使用,直接上代码

    @RequestMapping(value = "/download")
    public void download(HttpServletRequest request,HttpServletResponse resp) {
        
        //获取数据库中的文件路径,具体根据业务需求,例如:WEB-INF/download.xlsx
        String urlPath = "数据库的路径或者其他路径";
        //获取项目的真实路径,例如:D://project/download/
        String realPath = request.getServletContext().getRealPath("/");
        //文件真实路径,例如:D://project/download/WEB-INF/download.xlsx
        String path = realPath + File.separator + urlPath;
        File file = new File(path);
        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        //下载到本地的文件名,例如:abc.xlsx(注意:这里跟路径中的文件名区分开)
        String downloadName = "你要下载的文件名";
        resp.setHeader("Content-Disposition", "attachment;filename=" + downloadName );
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值