隨筆-348  評論-598  文章-0  trackbacks-0

          項目中所有的文檔全部壓縮之后存儲到數據庫,所以需要我們每次從數據庫讀取二進制然后發送到客戶端進行下載。如何在JSF里面這樣做呢?
          首先對外的方法這樣寫,我設置了按鈕的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獲得對象的實例,第二句是將所有相應信息傳輸給下載的公共方法,同時解壓縮了相應的二進制。

          下面是下載的公共方法
          /**
               * 向客戶端發送需要下載的文件
               * 
          @param faces 當前FacesContext
               * 
          @param content 文件的字節數組
               * 
          @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,經過測試,在IE6下(其他瀏覽器沒測試過),會導致無法打開臨時文件(我的是word文檔),而且經常出現無法下載文件。

          ---------------------------------------------------------
          專注移動開發

          Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
          posted on 2008-12-23 10:13 TiGERTiAN 閱讀(1402) 評論(0)  編輯  收藏 所屬分類: JavaJSF
          主站蜘蛛池模板: 西吉县| 浦东新区| 鞍山市| 广西| 淳化县| 增城市| 平南县| 阿拉善右旗| 贵阳市| 开远市| 大同县| 炉霍县| 班玛县| 崇礼县| 伊春市| 安远县| 凉山| 房山区| 丁青县| 凭祥市| 马鞍山市| 双鸭山市| 乳源| 祁门县| 阜新市| 朝阳区| 平果县| 南投市| 孝感市| 景洪市| 新乐市| 沂源县| 城步| 绥中县| 博罗县| 凤凰县| 阿图什市| 晋州市| 澎湖县| 宁晋县| 平泉县|