gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:59:59 25 4
gpt4 key购买 nike

我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com