通過JSF下載文件,不管這個文件是物理存在的,還是由服務器內存中生成的。
用戶從頁面點擊連接(link),下載相關的文件,該文件存在服務器端,或者由服務器端生成文件流,沒有物理文件;下載后頁面不跳轉。
JSP代碼:
<h:commandLink actionListener="#{productBean.downloadAction}" styleClass="highLightLink">
<h:outputText value="download"/>
<f:param name="productId" value="#{productBean.id}"/>
</h:commandLink>
Backing bean設計及代碼:
注意這是個Action listener方法,沒有返回值,并且有javax.faces.event.ActionEvent參數
public void downloadAction(ActionEvent event) {
try {
String fileName="D:\\temp\\images\\products\\" + this.id + ".xls";
logger.debug("file name=" + fileName);
ByteArrayOutputStream baos=this.serviceLocator.getFileService().downloadFile(fileName); //調用Service方法,獲得文件的ByteArrayOutputStream
HttpServletResponse response=FacesUtils.getServletResponse();
response.setHeader("Content-disposition", "attachment; filename=" + id+ ".xls" ); //不是內嵌顯示(inline),而是作為附件下載
response.setContentLength(baos.size());
ServletOutputStream sos=response.getOutputStream();
baos.writeTo(sos);
baos.close();
sos.flush();
} catch (IOException ex) {
logger.debug(ex);
}
}
Service代碼:
這個實現是一個從已經存在的物理文件獲得輸出流的范例,至于由Server在內存中生成輸出流也是一樣處理,例如生成一個Excel文件,再讓用戶下載。
public ByteArrayOutputStream downloadFile(String fileName) throws IOException {
FileInputStream fis=new FileInputStream(fileName);
BufferedInputStream bis=new BufferedInputStream(fis);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(baos);
int i;
while((i=bis.read())!=-1) {
bos.write(i);
}
bos.flush();//提交文件流,很關鍵
bis.close();
return baos;
}
posted on 2008-11-27 11:25
Vincent-chen 閱讀(601)
評論(0) 編輯 收藏 所屬分類:
JSF