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
          主站蜘蛛池模板: 霍林郭勒市| 舟山市| 洪洞县| 临邑县| 广水市| 井陉县| 逊克县| 福清市| 石门县| 桐梓县| 邵阳县| 阿勒泰市| 齐河县| 黄冈市| 大悟县| 江源县| 安达市| 永吉县| 天津市| 丽江市| 马龙县| 乐昌市| 上栗县| 镇坪县| 沙坪坝区| 竹溪县| 吉林市| 横山县| 乌兰浩特市| 永年县| 来宾市| 山阳县| 肥西县| 旺苍县| 页游| 长春市| 黄浦区| 平顶山市| 平塘县| 金平| 喀什市|