在primefaces中绑定文件下载的参数

时间:2014-03-05 13:08:41

标签: java primefaces

我想在primefaces中下载一个名称可能不同的文件。

以下是控制器的代码

@ManagedBean(name="fileDownloadController", eager = true)
@ViewScoped
public class FileDownloadController implements Serializable{

private StreamedContent file;  

private String fileName;

public FileDownloadController() {   
  System.out.println("FileDownloadController sans arg");
  System.out.println("getFileName:" + fileName);

  InputStream stream = null;  
  try {
     stream = new FileInputStream("D:/myFileDir/"+fileName);
  } catch (FileNotFoundException ex) {
    Logger.getLogger(FileDownloadController.class.getName()).log(Level.SEVERE, null, ex);
   }
   file = new DefaultStreamedContent(stream, "image/jpg", fileName);  
  }
}

这是xhtml

<c:forEach  items="#{myBean.files}" var="file" >
   <p:row>
      <p:column>
         <p:commandButton id="downloadLink" value="#{file.fileName}" ajax="false" onclick="PrimeFaces.monitorDownload(start, stop)" icon="ui-icon-arrowthichk-s" >  
            <f:setPropertyActionListener target="#{fileDownloadController.fileName}" value="#{file.fileName}"/>
            <p:fileDownload value="#{fileDownloadController.file}" />  
         </p:commandButton>   
     </p:column>
   </p:row>
 </c:forEach>   

问题是在控制器中fileName为null,因此未正确配置f:setPropertyActionListener。 但是,我找不到解决方案。

1 个答案:

答案 0 :(得分:2)

为什么不直接传递fileName ...

@ManagedBean(name="fileDownloadController", eager = true)
@ViewScoped
public class FileDownloadController implements Serializable{

   public StreamedContent generateFile(String fileName) {   
      InputStream stream = null;  
      try {
        stream = new FileInputStream("D:/myFileDir/"+fileName);
      } catch (FileNotFoundException ex) {

      }
      return new DefaultStreamedContent(stream, "image/jpg", fileName);  
   }

}

XHTML

<p:commandButton id="downloadLink" value="#{file.fileName}" 
                 ajax="false" onclick="PrimeFaces.monitorDownload(start, stop)" 
                 icon="ui-icon-arrowthichk-s" >
        <p:fileDownload value="#{fileDownloadController.generateFile(file.fileName)}" />  
 </p:commandButton> 

希望这有帮助。