1. 程式人生 > >如何在jsp頁面下載後臺伺服器返回的資料並儲存為txt格式

如何在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,裡面已經存在我儲存進去的內容  “你好啊!。。”