8

我想使用 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()" />

托管豆:

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>在一起?

4

1 回答 1

10

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

如果切换到 ajax-compatible<p:fileUpload mode="advanced">确实不是一个选项,那么最好的选择是升级到 JSF 2.2 并改用其新的本机<h:inputFile>组件。它还显示在浏览器默认外观中,并且能够通过隐藏的 iframe 技巧模拟 ajax 体验。

也可以看看:


与具体问题无关,您的操作方法中的这两个参数fileUpload()是完全没有必要的。只是

action="#{itemBean.fileUpload}"

public void fileUpload() {
    // ...
}

删除process="@this"属性后效果一样好。

于 2013-11-15T16:34:04.743 回答