項目背景:使用了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項目中考慮請求位址能通路到該檔案。