Null in PrimeFaces component UploadFile

0

I'm having trouble retrieving this file, file , in my bean.

.xhtml

<h:form id="form" enctype="multipart/form-data">
 <p:fileUpload value="#{bean.file}" 
                    skinSimple="true" mode="simple" />
 <p:commandButton value="Enviar" ajax="true"
                    action="#{bean.addFile}" /></h:form>

Bean.java

@ManagedBean
@ViewScoped
public class Bean{

    private UploadedFile file;


    public UploadedFile getFile() {
        return file;
    }

    public void setfile(UploadedFile file) {
        this.file = file;
    }

    public void addFile() {
        try {
            String fileName = file.getFileName();
            File fileOut = new File(fileName);

            FileOutputStream fileOutputStream = new FileOutputStream(fileOut);
            fileOutputStream.write(file.getContents());
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

When trying to access the file attribute, in the addFile() method, called by commandButton , the file attribute is not set to the file I uploaded, it is set to null. I can not find the problem, I have researched in several sources and I did not succeed.

The imports:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.model.UploadedFile;
    
asked by anonymous 28.06.2017 / 21:54

1 answer

1

I see two points that need attention:

  • Using ajax="true" in the commandButton component when used in set with the component FileUpload , where it is configured to use simple mode (% w / w). This is due to the fact that the component in the simple version does not support mode="simple" requests. If you really need this support, you can use advanced mode ( ajax ).

  • Using mode="advanced" in the action component is wrong, because commandButton should be used when there is intention to navigate between pages, instead use action , which is used in cases where you need to execute logic related to the view, where there is no need to change pages.

  • Here's an example of how it would look:
    <h:form enctype="multipart/form-data">
        <p:fileUpload value="#{bean.file}" mode="simple" skinSimple="true"/>
        <p:commandButton value="Enviar" ajax="false" actionListener="#{bean.addFile}"/>
    </h:form>
    
        
    28.06.2017 / 22:28