项目背景:使用了Spring MVC框架,在JSP页面嵌入一个第三方的开发的Active控件,客户端IE浏览器一般没有安装过该控件,需要在jsp页面提供自动下载和安装,控件就可以使用了。常见的就是下载扩展名为.cab的文件。
步骤一、Jsp前端引入对象
在JSP页面相应位置引入<object>标签,能起到自动下载xxx.cab文件是codebase属性,该属性应该是一个request请求,需要后台去处理该请求,见步骤二。
<pre class="html" name="code"><%@ page language="java" contentType="text/html; charset=UTF-8"
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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<object id="WebPDF" width="100%" height="600px" classid="clsid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" codebase="<%=basePath%>xxx.cab#version=1,1,0,0" VIEWASTEXT>
</object>
</body>
</html>
步骤二、Java后端获取请求,并下载文件到前端
/**
* 从服务器下载金格签章组件
* @param model
* @return
*/
@RequestMapping(value="/xxx.cab",method=RequestMethod.GET)
public ModelAndView getxxxComponent(HttpServletRequest request,
HttpServletResponse response){
response.setCharacterEncoding("UTF-8");
String filePath = "views\\mytask\\";
String fileName = "xxx.cab";
String contentType = "application/octet-stream";
try {
download(request,response,filePath,fileName,contentType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 下载文件
* @param request
* @param response
* @param filePath 文件在服务器的相对路径
* @param fileName 文件下载后的文件名
* @param contentType 文件类型
* @throws Exception
*/
public void download(HttpServletRequest request,
HttpServletResponse response, String filePath,String fileName,
String contentType) throws Exception {
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext().getRealPath("/");
String downLoadPath = ctxPath + filePath + fileName;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[1024*8];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.flush();
bos.close();
}
常见的问题:不能自动下载,请注意codebase属性是一个请求,把xxx.cab文件与普通的html文件放在同目录能提示安装,但是java web项目中考虑请求地址能访问到该文件。