在jsf配置文件裡面指定呈現視圖地頁面,並在頁面上設置響應頭信息
㈡ jsf 為什麼excel文件下載後變成zip格式,最好有代碼,謝謝
不會吧?我做的下載頁面雖然不是純JSF的,傳遞參數是用的JSF,而且解決了中文亂碼問題,包括文件名,文件內容。希望對你有幫助。
下載請求頁面傳遞過來的參數:
<rich:column>
<h:outputLink value="file.jsp" rendered="true">
<f:param name="docId" value="#{item.id.docId}" / <f:param name="revNo" value="#{item.id.revNo}" />
<f:param name="attachmentNo" value="#{item.id.attachmentNo}" />
<f:param name="filename" value="#{item.fileName}" />
<f:param name="storageName" value="#{item.storageName}" />
<h:outputText value="#{item.fileName}" />
</h:outputLink>
</rich:column>
執行請求的file.jsp 下載頁面
<%@page language="java" contentType="application/octet-stream" pageEncoding="utf-8"%>
<%@page import="java.io.*,java.util.*,java.net.URLEncoder"%>
<%response.reset();
String ATTACHMENTSTOREPATH = File.separator + "local"
+ File.separator + "uploads" + File.separator + "wf"
+ File.separator + "cpi";//此處以CPI為例
int docId = 0;
int revNo = -1;
int attachmentNo = 0;
String filename = null;
String storageName = null;
try {
docId = Integer.parseInt(request.getParameter("docId"));
revNo = Integer.parseInt(request.getParameter("revNo"));
attachmentNo = Integer.parseInt(request.getParameter("attachmentNo"));
//在火狐瀏覽器下載,含空格的文件名會出現異常,於是將空格用下劃線代替
filename = (new String(request.getParameter("filename").
getBytes("ISO-8859-1"),"UTF-8")).replace(" ", "_");
//將空格轉化為下劃線後重新對文件名進行UTF-8編碼
filename = java.net.URLEncoder.encode(filename, "UTF-8"); storageName = request.getParameter("storageName");
} catch (NumberFormatException nfe) {
}
if (docId >= 0 && revNo > -1 && attachmentNo >= 0) {
String filePath = null;
filePath = ATTACHMENTSTOREPATH + File.separator + storageName;
response.setContentType("application/octet-stream");
//因為瀏覽器會將字元GBK編碼,所以從資料庫獲得的UTF-8需要轉換成GBK
//UTF-8一個漢字24位,GBK一個漢字16位
//Start UTF-8 to GBK(相對以前的程序主要就是修改了這里)
String str=filename;
StringBuffer sb = new StringBuffer();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char)Integer.parseInt(
str.substring(i+1,i+3),16));
}
catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
i += 2;
break;
default:
sb.append(c);
break;
}
}
String result = sb.toString();
result= new String(result.getBytes("ISO-8859-1"),"UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=" + new String(result.getBytes("GBK"),"ISO-8859-1"));
//End UTF-8 to GBK
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(response.getOutputStream());
bis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[1024];
int n = -1;
while ((n = bis.read(buffer)) > -1) {
bos.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
bis = null;
bos = null;
}
}
%>