文件下载

使用ajax+servlet实现文件下载

前端代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
    </head>
    <body>
            <button  id="download" style="margin: 20px">下载图片</button>

        <script>

            $('#download').click(function () {
                $.ajax({
                    type:"get",
                    url:"download.do",
                    success:function (data){
                        window.location.href=this.url;
                    }
                })
            })
        </script>
    </body>
</html>

后端代码

@WebServlet("/download.do")
public class DownloadFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = req.getServletContext().getRealPath("\\WEB-INF\\classes\\xiaomai.png");
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        System.out.println(fileName);
        //设置下载文件的响应头
        // 为了防止文件名是中文响应回去时乱码使用URLEncoder.encode(fileName,"UTF-8")进行编码
        resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        FileInputStream input = new FileInputStream(realPath);
        byte[] buff = new byte[1024];
        int len =0;
        ServletOutputStream out = resp.getOutputStream();
        while ((len = input.read(buff))>0){
            out.write(buff,0,len);
        }
        req.setAttribute("msg","hello");
        input.close();
        out.close();
        
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值