項目中所有的文檔全部壓縮之后存儲到數(shù)據(jù)庫,所以需要我們每次從數(shù)據(jù)庫讀取二進(jìn)制然后發(fā)送到客戶端進(jìn)行下載。如何在JSF里面這樣做呢?
首先對外的方法這樣寫,我設(shè)置了按鈕的actionListener的屬性
public void viewContent(ActionEvent event)

{
try

{
ParkLawDTO obj = this.getEnterpriseEnterInBODelegate().getParkLawById(((ParkLawDTO)this.getParkLawDataModel().getRowData()).getParkLaw().getPlId());
Common.downloadFile(FacesContext.getCurrentInstance(), ZipHelper.unzip(obj.getParkLaw().getLawContent()), obj.getParkLaw().getLawName()+".doc", "application/msword;charset=utf-8");

}catch(Exception e)
{
info("下載文件出錯", e);
}
}
第一句是從WebService獲得對象的實(shí)例,第二句是將所有相應(yīng)信息傳輸給下載的公共方法,同時解壓縮了相應(yīng)的二進(jìn)制。
下面是下載的公共方法

/** *//**
* 向客戶端發(fā)送需要下載的文件
* @param faces 當(dāng)前FacesContext
* @param content 文件的字節(jié)數(shù)組
* @param fileName 客戶端接收的文件名
* @param contentType http的content-type
*/
public static void downloadFile(FacesContext faces, byte[] content, String fileName, String contentType)

{
try

{
HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
response.setHeader("Content-disposition", "filename="+ URLEncoder.encode(fileName, "utf-8"));
response.setContentType(contentType);
response.setContentLength(content.length);
ServletOutputStream sos = response.getOutputStream();
sos.write(content);
sos.flush();
sos.close();
//需要呼叫Complete
faces.responseComplete();

}catch(Exception e)
{
e.printStackTrace();
}
}
Content-disposition中一定不可以加attachment,經(jīng)過測試,在IE6下(其他瀏覽器沒測試過),會導(dǎo)致無法打開臨時文件(我的是word文檔),而且經(jīng)常出現(xiàn)無法下載文件。
---------------------------------------------------------
專注移動開發(fā)
Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2008-12-23 10:13
TiGERTiAN 閱讀(1395)
評論(0) 編輯 收藏 所屬分類:
Java 、
JSF