java - 在 primefaces 中绑定(bind)文件下载参数

标签 java primefaces

我想在 primefaces 中下载一个名称可以变化的文件。

这是 Controller 的代码

@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>   

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

最佳答案

为什么不直接传递文件名...

Bean

@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> 

希望这有帮助。

关于java - 在 primefaces 中绑定(bind)文件下载参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22198707/

相关文章:

java - 使用 Dr.Java,为什么 ♂ 在交互 Pane 中与编程时的值不同

java - java中的模糊逻辑

java - Windows -cp Mainclass 无法加载

javascript - 如何从命令按钮中取消选择 primefaces selectCheckboxMenu 中的所有元素

java - @Value 注解 & NullPointerException

css - 隐藏 <p :column> using CSS

java - 在 eclipse maven 中链接源文件夹时出现错误

java - JUnit 预期异常

java - p :fileDownload with dialog and loading status 的策略

primefaces - 如何打开 p :dialog inside a js file?