不啰嗦了,直接上代码,依赖jquery,下面代码可以直接复制到你的项目作为公共方法
前端封装代码,作为公共方法:
//postDownload.js
/**
* 下载文件,以POST的方式提交
* @param options{url,data}
* 使用方式
* postDownload({
* url:'xxx.download', //请求的url
* data:{name:xxx,age:xxx},//要发送的数据
* callback:function(){}//提交表单之前回调的函数,比如关闭下载框之类
* });
*
*/
function postDownload(options) {
var config = $.extend(true, { method: 'post' }, options);
var $form = $('<form target="_blank" method="' + config.method + '" />');
$form.attr('action', config.url);
for (var key in config.data) {
$form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
}
$(document.body).append($form);
if(config.callback != undefined){
config.callback();
}
$form.submit();
$form.remove();
}
如何使用?请看下面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Post Download Example</title>
<script type="text/javascript" src="jquery.js"></script><!-- 依赖jquery路径 -->
<script type="text/javascript" src="postDownload.js"></script><!-- 上面代码的文件路径 -->
<script type="text/javascript">
$(function(){
$('#downloadBtn').click(function(){
postDownload({
url:'PostDownloadServlet', //请求的url
data:{'name':$('#name').val()},//要发送的数据
callback:function(){
alert('关闭对话框...执行完我后才会下载哦,这个函数可以没有的,清空文本..');
$('#name').val('');
}//提交表单之前回调的函数,比如关闭下载框之类
});
});
})
</script>
</head>
<body>
Name:<input id="name" name="name" type="text"/>
<button id="downloadBtn">点我下载</button>
</body>
</html>
后台代码,随便写的,只为了测试使用,不关心可以略过了:
/**
* Servlet implementation class PostDownloadServlet
*/
@WebServlet("/PostDownloadServlet")
public class PostDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
System.out.println("name="+request.getParameter("name"));
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=\"file.xlsx\";target=_blank");
String filePath = this.getServletContext().getRealPath("/file.xlsx");
FileInputStream fis = new FileInputStream(new File(filePath));
ServletOutputStream ops = response.getOutputStream();
byte[] buffer = new byte[1024];
int n = 0;
while (-1 != (n = fis.read(buffer))) {
ops.write(buffer, 0, n);
}
fis.close();
ops.flush();
ops.close();
}
}
运行结果图: