文件下载Primefaces不工作,不做任何动作

时间:2017-01-25 12:51:18

标签: jsf primefaces download

单击“下载”按钮时,actionListener在使用ajax =“false”状态时不起作用,但在不使用ajax =“false”时,actionListener工作但不下载文件。

<html xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:tsc="http://java.sun.com/jsf/composite">

<h:form>
<p:commandButton immediate="true" value="#{msgs.common_click_download}"
    icon="ui-icon-arrowthick-1-s" process="@this"
    rendered="#{manehHelperMB.isFileExist('/home/hazemelshenawy/111.txt')}">
    <p:fileDownload process="@this" contentDisposition="inline"
        value="#{fileDownloaderMB.downloadFile('/home/hazemelshenawy/111.txt')}" />
</p:commandButton>

 </h:form>
  </html>

此代码java

public class FileDownloaderBean implements Serializable {
private DefaultStreamedContent file;

public DefaultStreamedContent downloadFile(String filePath) {
    if (filePath == null || filePath.isEmpty())
        return new DefaultStreamedContent();
    try {
        File fi = new File("/home/hazemelshenawy/111.txt");
        InputStream input = new FileInputStream(fi);
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        try {
            file = new DefaultStreamedContent(input,
                    externalContext.getMimeType(URLEncoder.encode(fi.getName(), "UTF-8")), fi.getName());
        } catch (UnsupportedEncodingException e) {
            CommonUtils.log(e);
        }

    } catch (FileNotFoundException e) {
        CommonUtils.log(e);
    }
    return file;
  }
 }

1 个答案:

答案 0 :(得分:0)

使用p:fileDownload时,p:commandButton中不需要ActionListener属性,但您应该Primefaces fileDownload Homepage

中所述的ajax="false"

尝试正确设置文件路径。 例如;在.xhtml文件中

rendered="#{manehHelperMB.isFileExist('D:\\home\\hazemelshenawy\\111.txt')}">
value="#{fileDownloaderMB.downloadFile('D:\\home\\hazemelshenawy\\111.txt')}"

和java类

File fi = new File("D:\\home\\hazemelshenawy\\111.txt");

另外你应该有setter和getter方法:

public DefaultStreamedContent getFile() {
        return file;
    }
public void setFile(DefaultStreamedContent file) {
        this.file = file;
    }
相关问题