在页面按钮上绑定一个onclick事件downLoadUserText();
跳转页面js方法:(downLoad.js)
function downLoadUserText(){
var filepath="/WEB-INF/views/download/";//文件路径
var fileName="文件名.docx";
window.location.href=ctx+"/downLoadController/downLoad?filepath="+filepath+"&fileName="+fileName;
}
java controller层:(DownLoadController )
package gov.nbeic.nbzwy.web.common;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("/downLoadController")
@Controller
public class DownLoadController {
//下载文件
@RequestMapping(value = "/downLoad")
public String downLoadFile(Model model,@RequestParam("filepath") String filepath,@RequestParam("fileName") String fileName){
model.addAttribute("filepath", filepath);//将文件存放路径存放
model.addAttribute("fileName", fileName);//将文件名称存放
return "/download/down";
}
}
下载页面jsp页面(down.jsp)
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.File"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>文档下载保存中转页面</title>
</head>
<!--
*文件名:down_center.jsp
-->
<body>
<%
String root = getServletContext().getRealPath(""); //得到网站绝对路径
String filepath = (String)request.getAttribute("filepath"); //设置文件存放的相对路径
String fileName =(String)request.getAttribute("fileName");//设置文件名称
System.out.println(root + filepath + fileName);
// 设置响应头和下载保存的文件名
response.reset();
//response.setContentType("application/octet-stream");
//response.addHeader("Content-Disposition", "filename=\"" + myName + "\"");
response.setContentType("application/octet-stream; charset=GBK");
//linux
response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"),"iso8859-1") + "\"");
//新建文件输入输出流
OutputStream output = null;
FileInputStream fis = null;
try{
//新建File对象,同样你可以选择你自己的InputStream
File f = new File(root + filepath + fileName);
//新建文件输入输出流对象
output = response.getOutputStream();
fis = new FileInputStream(f);
//设置每次写入缓存大小
byte[] b = new byte[(int)f.length()];
//out.print(f.length());
//把输出流写入客户端
int i = 0;
while((i = fis.read(b)) > 0){
output.write(b, 0, i);
}
output.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(fis != null){
fis.close();
fis = null;
}
if(output != null){
output.close();
output = null;
out.clear();
out = pageContext.pushBody();
}
}
%>
</body>
</html>