如何在jsp页面下载后台服务器返回的数据并保存为txt格式

首先新建一个jsp页面,jsp代码如下

<html>
 <head>
   <base href="<%=basePath%>">
   <title>My JSP 'download.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is mypage">
    <!--
    <linkrel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#downloadbtn').click(function(){
            alert("click");
            var taskid="11";
            //$.post("downLoad",{type:"download",TaskId:taskid});
var form=$("<form id='formmodify'action='downLoad' method='post'></form>");
             form.append("<input type='hidden' name='taskid' value='"+taskid+"'>");
             form.submit();
          });
        });
    </script>
 </head>
 
 <body>
   This is my JSP page. <br>
   <input id="downloadbtn" type="button"  value="download">
 </body>
</html>


由jsp页面请求服务器后,将要请求的内容发送至服务器端的servlet(downLoad),服务器知道有浏览器请求后,将相应的内容写入txt文件的输出流,并由response返回客户端。

后台程序如下所示:

public void doPost(HttpServletRequestrequest, HttpServletResponseresponse)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
          // 生成txt
        try {
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_kkmmss ");
            String random = sdf.format(d);
            String targetFile = random + ".txt";
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + targetFile + "\"");
            OutputStream os = response.getOutputStream();
            String temp = "你好啊!    "+random;
            System.out.println(temp);
            os.write(temp.getBytes());
            os.close();
            response.flushBuffer();
        } catch (Exceptione) {
            System.out.println("生成txt文件时出错:");
            e.printStackTrace();
        }
    }


打开页面点击如下所示download,请求穿回到后端服务器

然后,后端响应后,浏览器提供下载,默认就保存在了桌面

这个时候,桌面上就已经,出现了这个txt文件

打开txt,里面已经存在我保存进去的内容  “你好啊!。。”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值