0

I need to upload a file using <h:inputFile>. I am using the following code:

<h:inputFile id="inputFile" value="#{bean.uploadedFile}" styleClass="hidden">
    <f:ajax listener="#{bean.processFile}"/>
</h:inputFile>

...

<button onclick="$('#inputFile').click();">
    Choose file
</button>

As you can see, I am hiding the ugly <h:inputFile> and just simulating a click on it using a button.

When I click the button, the file explorer is shown and I can choose a file, but, once selected, the page reloads and the processFile method is never called.

If I remove the hidden class for the <h:inputFile>, click on it and select a file, everything works perfectly.

I tried simulating the click with the <h:inputFile> visible, but the same wrong behavior occurs.

Is there anything I can do to simulate the click and retain the <h:inputFile> hidden.

I am using Wildfly with JSF 2.3.

Thanks

Jucaalpa
  • 310
  • 1
  • 4
  • 15

1 Answers1

0

I found a solution based on CSS only and without the need to use Javascript for simulating the click:

<label class="input-type-fix">
    <h:inputFile value="#{bean.uploadedFile}">
        <f:ajax listener="#{bean.processFile}"/>
    </h:inputFile>
    <span>Choose file</span>
</label>

The CSS:

.input-type-fix input[type="file"] {
    position:absolute;
    top: -1000px;
}

This way you dont't need to hide the input file and you could add the style you want to the label surrounding the input file. I am using bootstrap, so a posible style could be the following one:

<label class="btn btn-primaryinput-type-fix">
    <h:inputFile value="#{bean.uploadedFile}">
        <f:ajax listener="#{bean.processFile}"/>
    </h:inputFile>
    <span>Choose file</span>
</label>

As you can see I just add bootstrap classes to the surrounding label.

The question where I found the solution (most of it) is the following one: Cross-browser custom styling for file upload button

Jucaalpa
  • 310
  • 1
  • 4
  • 15