JSF를 사용한 파일 다운로드

1944 단어
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);
    }   
  }

서비스 코드: 이 구현은 이미 존재하는 물리 파일에서 출력 흐름을 얻는 예이다. 서버가 메모리에서 출력 흐름을 생성하는 것도 마찬가지로 처리한다. 예를 들어 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;
  }

좋은 웹페이지 즐겨찾기