Search code examples
file-uploadjsf-2primefacescommandbutton

How to upload file of p:fileUpload using command button instead of upload button


Iam using JSF2.1 along with primefaces for uploading file.In my application i have to add the file dynamically on creating a record.But when i use i cant write the code for uploading my file during save.I want the file to be uploaded on click of save only and not during upload. Can anyone help me how to implement this

public String handleFileUpload(FileUploadEvent event) throws IOException {  
    FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);  
    UploadedFile file = event.getFile();

    String prefix = FilenameUtils.getBaseName(file.getFileName());
    String suffix = FilenameUtils.getExtension(file.getFileName());


    String path = "C:/apache-tomcat-7.0.47/webapps/ROOT/WEB-INF/images";

     ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();


    File fileToDirectory = File.createTempFile(prefix + "-", "." + suffix, new File(path));

    InputStream inputStream = event.getFile().getInputstream();
    String fileName = event.getFile().getFileName();

    OutputStream outputStream = new FileOutputStream(fileToDirectory);

    byte[] buffer = new byte[1024];

    int length;
    //copy the file content in bytes 
    while ((length = inputStream.read(buffer)) > 0){

        outputStream.write(buffer, 0, length);

    }

    inputStream.close();
    outputStream.close();
    return path+fileName;


}

I need to have this code on save but i cant get event during save


Solution

  • That isn't possible with auto mode. Use the basic mode instead. Then you can bind the input value to an UploadedFile property directly. This only requires disabling Ajax.

    E.g.

    <h:form enctype="multipart/form-data">
        ...
        <p:fileUpload mode="simple" value="#{bean.file}" />
        ...
        <p:commandButton value="Save" action="#{bean.save}" ajax="false" />
    </h:form>
    

    with

    private UploadedFile file; // +getter+setter
    
    public void save() {
        try (InputStream input = file.getInputStream()) {
            // ...
        }
    }
    

    The alternative is to migrate to standard JSF <h:inputFile> component which was introduced in JSF 2.2. Then you can continue using Ajax.

    E.g.

    <h:form enctype="multipart/form-data">
        ...
        <h:inputFile value="#{bean.file}" />
        ...
        <p:commandButton value="Save" action="#{bean.save}" />
    </h:form>
    

    with

    private Part file; // +getter+setter
    
    public void save() {
        try (InputStream input = file.getInputStream()) {
            // ...
        }
    }
    

    See also: