您的位置:首页 > Web前端 > JavaScript

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

2016-06-24 18:41 736 查看
首先新建一个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,里面已经存在我保存进去的内容  “你好啊!。。”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息