文件下载

本文介绍如何通过前端实现文件下载,用户可以访问http://localhost:8080/down.jsp下载各种格式的文件。
摘要由CSDN通过智能技术生成

文件下载

可以下载任何格式的文件

     @RequestMapping("/down")
    public void down(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // String name = "Depot_Management/src/main/webapp/images/a.jpg";
        // File f = new File(name);
        //(request.getSession().getServletContext().getRealPath("/")+"/images/a.jpg")获取相对路径
        File f = new File(request.getSession().getServletContext().getRealPath("/") + "/images/QQPCMgr_1100106221.exe");

        System.out.println(f);
        if (f.exists()) {
            FileInputStream fis = new FileInputStream(f);
            String filename = URLEncoder.encode(f.getName(), "utf-8"); //解决中文文件名下载后乱码的问题
            byte[] b = new byte[fis.available()];
            fis.read(b);
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename + "");
            //获取响应报文输出流对象
            ServletOutputStream out = response.getOutputStream();

            //输出
            out.write(b);
            //刷新
            out.flush();
            //关闭
            out.close();
        }
    }

前端

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.4.1.min.js"></script>
    <script>
        $(function () {
            $("#id").click(function () {
            var a =confirm("是否进行下载");
            if (a==true){
                return true;
            }else {
                return false;
            }
            })
        })

    </script>
</head>
<body>
<a href="down" id="id">文件</a>

</body>

</html>

访问:http://localhost:8080/down.jsp进行下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值