如何在模式简单和ajax =“true”的情况下使用<p:fileupload>?</p:fileupload>

时间:2013-11-15 08:38:13

标签: ajax file-upload jsf-2 primefaces

我想使用PrimeFaces和ManagedBean上传文件。我希望使用p:fileUpload和mode =“simple”。

XHTML代码:

    <p:fileUpload id="fileId" mode="simple" value="#{itemBean.upFile}"
        fileLimit="1" />
    <p:commandButton ajax="true" value="Upload File" update="messagess"
                     id="save-btn"
                     actionListener="#{itemBean.fileUpload(itemBean.upFile,itemBean.hiddenFileName)}"
                     process="@this" oncomplete="showImage()" />

ManagedBean:

public void fileUpload(UploadedFile uploadFile, String hiddenKey) {  
    String keyFileName = hiddenKey;

    boolean validFile = true;
    String expression = "([^\\s]+(\\.(?i)(gif|jpg|jpeg|gif|png|PNG|GIF|JPG|JPEG|bmp))$)";
    if((uploadFile == null) ) {
        validFile = false;
        FacesMessage msg = new FacesMessage("Error! "+ "Please select an image.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }  
    else {
    System.out.println("going to file upload"+uploadFile.getFileName()+"---hiddenKey"+keyFileName);
    if((!uploadFile.getFileName().matches(expression)) ) {
        validFile = false;
        FacesMessage msg = new FacesMessage("Error! "+ uploadFile.getFileName() + " is not an image.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    if(uploadFile.getSize() > 1000000) {
        validFile = false;
        FacesMessage msg = new FacesMessage("Error! "+ uploadFile.getFileName() + " size is too large.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    if (validFile) {
        // Do what you want with the file        
        try {
            //String extn =uploadFile.getFileName().substring(uploadFile.getFileName().lastIndexOf("."));


            copyFile(uploadFile.getFileName(), uploadFile.getInputstream());

            FacesMessage msg = new FacesMessage("Success! "+ uploadFile.getFileName() + " is uploaded.");  
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (IOException e) {
            e.printStackTrace();
            FacesMessage msg = new FacesMessage("Error! "+ uploadFile.getFileName()+ " not uploaded.");  
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }
    }
}  

我的问题是,我点击了命令按钮,并且未调用辅助bean中的方法。 如果我使用ajax="false",则会调用该方法,但页面会刷新。

如何一起使用ajax="true"<p:fileUpload>

1 个答案:

答案 0 :(得分:8)

<p:fileUpload mode="simple">不支持ajax。对不起,但这是故事的结尾。

如果切换到兼容ajax的<p:fileUpload mode="advanced">实际上不是一个选项,那么最好的办法是升级到JSF 2.2并使用新的原生<h:inputFile>组件。它还显示在浏览器默认的look'n'feel中,并且能够通过隐藏的iframe技巧模拟ajax体验。

另见:


对具体问题

无关fileUpload()操作方法中的这两个参数完全没必要。只是

action="#{itemBean.fileUpload}"

public void fileUpload() {
    // ...
}
删除process="@this"属性后,

可以正常工作。