創建export.jsp,將該jsp設置成文件下載:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% response.setHeader("Content-disposition","attachment; filename="+request.getAttribute("fileName")+".xls"); %>
<!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></title>
</head>
<body>
<%=request.getParameter("html") %>
</body>
</html>
不同瀏覽器之間會存在文件名亂碼問題,故增加處理類:
public class DownloadFileUtil {
/**
* @Description: 解決不同瀏覽器下載文件名亂碼
* @param request
* @param fileName
* @return
*
*/
public static void encodeDownloadFileName(HttpServletRequest request) {
request.setAttribute("fileName", encodeDownloadFileName(request.getHeader("USER-AGENT"),request.getParameter("name")));
}
public static String encodeDownloadFileName(String agent, String fileName) {
try {
if (null != agent && -1 != agent.indexOf("MSIE")) {
fileName = URLEncoder.encode(fileName, "utf-8");
} else {
fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileName;
}
}
最後我們就只需要訪問控制層,跳轉到該jsp就行了:
exportData : function(){
var submitForm = document.createElement("FORM");
submitForm.method = "POST";
submitForm.action ="../exportData.do";
var nameParam = document.createElement("input");
nameParam.type="text";
nameParam.name="name";
nameParam.value="目標";
submitForm.appendChild(nameParam);
var htmlParam = document.createElement("input");
htmlParam.type="text";
htmlParam.name="html";
htmlParam.value=$("#monthDiv").html()+"<br/><br/>"+$("#dailyDiv").html();
submitForm.appendChild(htmlParam);
document.body.appendChild(submitForm);
submitForm.submit();
document.body.removeChild(submitForm);
}
Ok了,這種方式簡單且跨瀏覽器也支持