国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

實例-用JSF實現文件下載

2019-11-18 16:24:46
字體:
來源:轉載
供稿:網友

  背景:
環境:Windows PRo 2000 + sp4; Tomcat 5.0.30, Myfaces 1.1.0(一定要用這個版本,否則會有Servlet response相關的錯誤,雖然文件還是可以下載), Spring 1.5。

用戶從頁面點擊連接(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;
  }
進入討論組討論。

(出處:http://m.survivalescaperooms.com)



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 仲巴县| 娄底市| 北流市| 仁寿县| 弥渡县| 渭南市| 汝阳县| 行唐县| 镇远县| 金川县| 舟曲县| 苏尼特左旗| 淳安县| 竹北市| 江都市| 旅游| 武乡县| 阿拉善盟| 永丰县| 安达市| 凉城县| 吉水县| 毕节市| 井冈山市| 武强县| 荔波县| 巨鹿县| 茌平县| 甘德县| 无为县| 上思县| 来宾市| 建瓯市| 桑植县| 崇左市| 肥乡县| 炎陵县| 隆化县| 汪清县| 弥渡县| 马公市|