<p:fileUpload> always give me null contents [duplicate]
Asked Answered
F

2

9

I'm trying to get working like what is documented in the primefaces user guide, and some posts founded there.

Upload file in JSF primefaces.

the environnement is : javaee full + jpa + jsf 2.2 + primefaces 4 + glassfish v4

I m posting again, because i have tried every sample and suggestion i have found on the web, without success.

I m able, to get the file uploaded name with : event.getFile.getFileName, but the content is always null

-------------Updates----------------------------

My xhtml page :

<h:form enctype="multipart/form-data">

                <p:outputLabel value="La photo :"/>
                <p:fileUpload fileUploadListener="#{personController.upload}"
        mode="advanced" 
        update="messages"
        sizeLimit="100000" 
        allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
                <p:growl id="messages" showDetail="true"/>

            </h:form>

my managed bean :

@Named(value = "personController")
@SessionScoped
public class PersonController implements Serializable {

    /**
     * Creates a new instance of PersonController
     */
    @Inject
    private PersonneFacade personneService;
    private Personne current;
    private Personne newPerson;
    private List<Personne> personnes;


    public PersonController() {
    }

    public List<Personne> getAll(){
        return personneService.findAll();
    }


    public void upload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        // Do what you want with the file

        System.out.println(event.getFile().getFileName());
        System.out.println("le fichier " + event.getFile().getContents());
        newPerson.setPhoto(event.getFile().getContents());
    }

my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>

     <!-- ############################################# -->
<!-- # File upload                                      # -->
<!-- ############################################# -->
<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>
        org.primefaces.webapp.filter.FileUploadFilter
    </filter-class>

</filter>

<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>


</web-app>

sure i have on my pom.xml :

<dependencies>
        <dependency>  
    <groupId>org.primefaces</groupId>  
    <artifactId>primefaces</artifactId>  
    <version>4.0</version>  
</dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.0-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>

when i m triyng to upload i got on the glassfish output log:

INFO:   mdmx.jpg
INFO:   le fichier null

any idea about ??

Faro answered 5/8, 2013 at 2:6 Comment(4)
Related: #8876318Cabin
i have tried what you suggest, but no success. On the chrome debug tool i got the http parameters and it seems to be correct, the content type is a "multipart/form-data". i can't found the problems cause !!Faro
I've checked the primefaces source. It looks like your ´File` is actually null which causes the NPE. If you have got the correct permissions setup (chmod & user/group rights) for /opt/upld then it's hard to guess.Gardener
I have noticed an error when starting Glassfish 4 server, it says : "WARNING: WELD-001529 An InjectionTarget implementation is created for a class org.primefaces.context.PrimePartialViewContextFactory which does not have any appropriate constructor.". I think this is the major cause of the NPE.Faro
F
16

I have solved this issue like folowing :

The upload worked for me when using : IOUtils.toByteArray(file.getInputstream());

the environnement is : Java EE 7(JPA, EJB, JSF 2.2.4), Glassfish V4, Primefaces 4

i give here the complete example, for reusing.

First : upload.xhtml

<h:form enctype="multipart/form-data">
    <p:fileUpload fileUploadListener="#{personController.handleFileUpload}" />
            <p:growl id="messages" showDetail="true"/>
</h:form>

Second : PersonController.java (the jsf managed bean) : package com.sos.fso.grh.controllers;

import com.sos.fso.grh.entities.Person;
import com.sos.fso.grh.services.PersonFacade;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.UploadedFile;

@Named
@SessionScoped
public class PersonController implements Serializable{

@Inject
private PersonFacade personService;

private Person current;
private Person newPerson;
private List<Person> personnes;

public void handleFileUpload(FileUploadEvent event) throws IOException {

    UploadedFile file = event.getFile();
    System.out.println(file.getFileName());

    byte[] foto = IOUtils.toByteArray(file.getInputstream());
    System.out.println(foto);
    newPerson.setPhoto(foto);
 //application code
}

}

Third : the web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>bootstrap</param-value>
    </context-param>
         <context-param>   
 <param-name>primefaces.UPLOADER</param-name>   
 <param-value>auto</param-value>
</context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
        </web-app>

if you have an entity bean "person" for example with a @Lob binary attribute, you can fill it with the byte data. to save the image (or file if you need).

to restore it on a

the view.xhtml

    <!DOCTYPE html>
<html xmlns="http://www.w3c.org/1999/xhtml"   
 xmlns:h="http://java.sun.com/jsf/html"   
 xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
    <h:form>
    #{personController.current.FName}

        <p:panelGrid columns="2">
        <p:outputLabel value="Nom :"/>
        <h:outputText value="#{personController.current.FName}" />

        <p:outputLabel value="Prénom :"/>
        <h:outputText value="#{personController.current.LName}" />

        <p:outputLabel value="Date de naissance :"/>
        <h:outputText value="#{personController.current.birthDate}" />

        <p:outputLabel value="photo :"/>
        <p:graphicImage value="#{personController.byteToImage(personController.current.photo)}" />
        </p:panelGrid>
        <p:commandLink value="retour a la liste" action="#{personController.showList}"/>
        </h:form>

</h:body>
</html>

and the PersonController Method to restore the image (This code is of BalusC from stackOverFlow )

public DefaultStreamedContent byteToImage(byte[] imgBytes) throws IOException {
ByteArrayInputStream img = new ByteArrayInputStream(imgBytes);
return new DefaultStreamedContent(img,"image/jpg");
}

thanks for everyone helped me.

thanks again

Faro answered 27/11, 2013 at 15:31 Comment(2)
Primefaces team should update their documentation to include IOUtils.toByteArray(file.getInputstream()) to the p:fileupload section. Works great!! Thank you!Kweiyang
I am facing same issue while upgrading jsf version from 2.1.x to 2.2.0 .('event.getFile().getContents()' throws 'NullpointerException' ) thanks You @Mohamed abdelbassatBrazilin
F
0

Include Apache-Commons IO and Fileupload API's to your app:

Freckly answered 5/8, 2013 at 5:18 Comment(1)
alredy do. i have on my maven dependency's apache commons-io and commons fileupload(the last is automatically required with primefaces 3.5)Faro

© 2022 - 2024 — McMap. All rights reserved.