需求是通过页面点击按钮打开或保存文件,如下图:
实现代码如下:
在需要导出的页面加上:
<script language="javascript"> <% String fileName = request.getAttribute("fileName")==null?null:(String)request.getAttribute("fileName"); if(fileName!=null && !"".equals(fileName)) { %> function toExcelFile() { var url = "../download.jsp?fileName=<%=fileName%>";//转向网页的地址; var name = "下载";//网页名称,可为空; var iWidth = 200;//弹出窗口的宽度; var iHeight = 120;//弹出窗口的高度; var iTop = (window.screen.availHeight-30-iHeight)/2; //获得窗口的垂直位置; var iLeft = (window.screen.availWidth-10-iWidth)/2; //获得窗口的水平位置;
window.showModalDialog(url,name,'dialogHeight:'+iHeight+'px;dialogWidth:'+iWidth+'px;dialogLeft:'+iLeft+';dialogTop:'+iTop+';center:yes'); }}toExcelFile(); <%}%> </script>
webRoot目录底下的download.jsp页面如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>文件下载</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 my page"> <style type="text/css"> .align-center{ margin:40 auto; /* 居中 这个是必须的,,其它的属性非必须 */ width:100px; /* 给个宽度 顶到浏览器的两边就看不出居中效果了 */ /*background:red;*/ /* 背景色 */ text-align:center; /* 文字等内容居中 */ } body{text-align:center;} </style> </head> <body> <% String fileName = request.getParameter("fileName"); %> <div class="align-center"> <a href="export_file/<%= fileName %>" title="请点击保存文件">生成的文件</a> </div> </body></html>
这样就可以了。
另外附上java打开文件的代码(无意中知道的):
Process p1 = Runtime.getRuntime().exec("cmd /c start "+fileURL);
转载请注明原文地址: https://ibbs.8miu.com/read-2210406.html