posts - 5,  comments - 7,  trackbacks - 0
          通過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 閱讀(607) 評論(0)  編輯  收藏 所屬分類: JSF
          主站蜘蛛池模板: 越西县| 沁阳市| 斗六市| 象山县| 资兴市| 衡水市| 东阳市| 石渠县| 昌黎县| 吉安县| 黄梅县| 上蔡县| 崇阳县| 南阳市| 东乡县| 太康县| 双鸭山市| 宿州市| 承德县| 泾川县| 自贡市| 南雄市| 来安县| 留坝县| 东台市| 刚察县| 肥西县| 乐山市| 友谊县| 八宿县| 黄浦区| 巨野县| 闻喜县| 雷州市| 太保市| 景宁| 鄂伦春自治旗| 长泰县| 开封市| 南昌县| 岳西县|