Search code examples
jsf-2primefacesopenfiledialog

Get file url in JSF 2.2


I am trying to make an openfiledialog in the backing bean, so that I can get the url of the local file. However it seems that the standard JSF library does not support open/save file dialog. Is there another way of getting an url of a file with something similar to openfiledialog?

Here is what has to happen: Click on a button --> send action to the backing bean --> show openfiledialog --> get url of the file --> add url of the file to a list of strings.

I am not sure how to accomplish the bold steps above. Is there someone who can give me any leads or help to accomplish this?

(I am using JSF & Primefaces, I would prefer not to use another external library if possible.)


Solution

  • Since you're using JSF 2.2 as well as Primefaces, why not use the primefaces component itself?

    Below is the Primefaces 5.0 showcase example for a basic file upload:

    <h:form enctype="multipart/form-data">
        <p:growl id="messages" showDetail="true" />
    
        <p:fileUpload value="#{fileUploadView.file}" mode="simple" skinSimple="true"/>
    
        <p:commandButton value="Submit" ajax="false" actionListener="#{fileUploadView.upload}" disabled="true" />
    </h:form>
    

    Managed Bean

    import org.primefaces.event.FileUploadEvent;
    import org.primefaces.model.UploadedFile;
    
    @ManagedBean
    public class FileUploadView {
    
        private UploadedFile file;
    
        public UploadedFile getFile() {
            return file;
        }
    
        public void setFile(UploadedFile file) {
            this.file = file;
        }
    
        public void upload() {
            if(file != null) {
                FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        }
    }
    

    The enctype attribute for the form is required. Also, for using Primefaces file upload, you need to setup certain context parameters and filters. You may refer the appropriate documentation for the same.