Ajax listener not working with inputFile

2019-09-19 10:38发布

问题:

First of all, I'm using JSF 2.2.7 and GlassFish 4 in NetBeans 8.0.
Second, sorry if I left any useful info out. This is my first question in here, so I may forget something. Also, english isn't my first language. Sorry for typos/grammar.

So, here's my problem: I'm uploading files with h:inputFile and I need an ajax listener for it.
After noticing that it wasn't working as I expected, I decided to do some testing with a listener that prints "Test", but it's never fired with h:inputFile. I've tried with h:commandButton and h:commandLink and they both work fine.
For further testing, I created a new project using the same test code and everything works, including the listener in h:inputFile.

What I want to know is why it doesn't work in my main project and why it works in the test project. What am I missing here? And how can I make it work in my main project?

Here are some (but not all, since I lost track) things that I've tried/checked so far, after looking for answers:

  • There are no nested forms. The said xhtml is in a ui:composition, but even taking that into account, there are no nested forms.
  • Its form has enctype="multipart/form-data"
  • I've tried changing the method to uploadTest(AjaxBehaviorEvent event) and the listener to listener="#{submitFormBean.uploadTest}" [without the ()]
  • I've played with the various event="..." and execute="..." (didn't think it would solve my problem, but, well, I had to try)

The code follows below:

xhtml

<h:form>
    <h:commandButton id="btnTest">
        <f:ajax listener="#{submitFormBean.uploadTest()}"/>` --> works in both projects`
    </h:commandButton>
</h:form>
<h:form>
    <h:commandLink id="lnkTest" value="Test">
        <f:ajax listener="#{submitFormBean.uploadTest()}"/>` --> works in both projects`
    </h:commandLink>
</h:form>
<h:form enctype="multipart/form-data">
    <h:inputFile id="fileTest">            
        <f:ajax listener="#{submitFormBean.uploadTest()}"/>` --> works only in test project`
    </h:inputFile>
</h:form>

bean

@ViewScoped
@ManagedBean(name = "submitFormBean")
public class SubmitFormBean{

    public SubmitFormBean() {
    }

    public void uploadTest(){
        System.out.println("Test");
    }
}

Thanks in advance!

回答1:

I was about to do what I needed in jQuery, but first I decided to try the following and it solved my problem:

right click project/properties/libraries
in the compile tab, I removed and readded the JSF 2.2.7 .jar

It was already there, but for some reason wasn't working. I still don't know what went wrong, but it's working now.



回答2:

With multipart/form-data in JSF form, you have to do additional configuration to make it works.

You can refer to other questions: commandButton/commandLink/ajax action/listener method not invoked or input value not updated

JSF 2.0 File upload

And

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null