Filippo1980
Filippo1980

Reputation: 2735

Upload a file on filesystem with Primefaces

I read many pages but, i'm sure, I did some errors somewhere and I can't do the upload of a file simply as It should be.

First, I'm developing using JSF2.0, Primefaces 3.2 and JPA2 on Glassfish 3.1 with Netbeans 7 and JDK 1.7.

The next thing that I must say is that I'm tringg to insert this code into an interface that will be extended from many others classes and that should store the files in many folders on filesystem! So now I will report what I wrote and, please, tell me where is the problem!

This is the code into web.xml:

<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    <init-param>
        <param-name>uploadDirectory</param-name>
        <param-value>D:/Cyborg/</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>  

The page that contains the p:uploadFile contains also many other form's fields and I will copy only what I think is of your interest:

...
<h:form method="POST">
    ...
    <h:outputLabel for="uploadFile" value="#{bundle.LabelUploadFile}" />
    <p:fileUpload value="#{progettiController.uploadFile}" mode="simple" />
    ...
    <h:commandLink action="#{progettiController.create}" value="#{bundle.SaveLink}" />
    ...

this is the code into the interface called AbstractController:

protected UploadedFile uploadFile;

public void setUploadFile(UploadedFile uploadFile) {
    this.uploadFile=uploadFile;
}

public UploadedFile getUploadFile() {
    return uploadFile;
}

and finally the method Create into ProgettiController:

public String create() {
    try {
        getFacade().create(current);
        System.out.println("Message: ProgettiController: Create: new row created successfully!");

        try {
            current=getFacade().findLast();
            String ext=uploadFile.getFileName();
            System.out.println("Message: ProgettiController: Create: FileName="+ext);

            ext=ext.substring(ext.lastIndexOf("."),ext.length());
            System.out.println("Messaggio: ProgettiController: ext="+ext);

            current.setNomeFile(ext.substring(0,ext.lastIndexOf(".")));
            current.setTipoFile(ext.substring(ext.lastIndexOf(".")+1,ext.length()));
            getFacade().edit(current);
            ext=urlFilesystem+current.getId()+ext.substring(ext.lastIndexOf(".")+1,ext.length());
            System.out.println("Message: ProgettiController: Create: posizione e nome del file="+ext);

            File oldFile= (File)uploadFile;
            File newFile= new File(ext);
            oldFile.renameTo(newFile);
        } catch (Exception e) {
            System.out.println("Messaggio: ProgettiController: Create: errore nel try legato al upload="+e.getMessage());
            e.printStackTrace();
        }

        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProgettiCreated"));
        recreateModel();
        System.out.println("Messaggio: ProgettiController: create try");
        return url+"List?faces-redirect=true";
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        System.out.println("Messaggio: ProgettiController: create catch="+e.getMessage());
        e.printStackTrace();
        return url+"List?faces-redirect=true";
    }
}

If I try this code the problem is that when the page call the method returns null into uploadFile, if I add the "enctype="multipart/form-data"" into h:form tag the application didn't call the method! Can someone help me? Thanks a lot!

Upvotes: 1

Views: 3999

Answers (2)

Younes AMIL
Younes AMIL

Reputation: 11

there's an error in your code causing the null pointer

        {..
        ext=ext.substring(ext.lastIndexOf("."),ext.length()); 
        // here ext contains the extension of the file only

        System.out.println("Messaggio: ProgettiController: ext="+ext);

        current.setNomeFile(ext.substring(0,ext.lastIndexOf(".")));
        // used the extension as the file name
        current.setTipoFile(ext.substring(ext.lastIndexOf(".")+1,ext.length()));
        // the file type is an empty string causing the error
        ..}

try the following

        {..
        ext=ext.substring(ext.lastIndexOf("."),ext.length()); 

        System.out.println("Messaggio: ProgettiController: ext="+ext);

       current.setNomeFile(uploadFile.getFileName().
                           substring(0,uploadFile.getFileName().lastIndexOf(".")));
        // the file name is setted properly
        current.setTipoFile(uploadFile.getFileName().
                           substring(uploadFile.getFileName().
                           lastIndexOf(".")+1,uploadFile.getFileName().length()));
        // the file type is setted properly
        ..}

Upvotes: 1

BalusC
BalusC

Reputation: 1108742

if I add the "enctype="multipart/form-data"" into h:form tag the application didn't call the method!

That would mean that the PrimeFaces file upload filter wasn't able to do its job properly. It is responsible for parsing a multipart/form-data request and providing the parsed data further to JSF in an understandable form (until the upcoming JSF 2.2 version, JSF does by default not support multipart/form-data requests).

That can have at least the following main reasons:

  • The <servlet-name> in the <filter-mapping> is incorrect. You need to make sure that it's exactly the same <servlet-name> of the <servlet> configuration of the FacesServlet in the same web.xml.

  • The Commons IO and FileUpload JARs are not in the webapp's runtime classpath. I don't use Netbeans, so I can't go in detail, but whatever way you use to include the JARs in the webapp, you need to make absolutely sure that they end up in /WEB-INF/lib folder of the deployed webapp. You can verify that by checking the deploy in the server. In Eclipse, that can among others be achieved by just dropping those JARs straight in exactly that folder of the web project.

  • You happen to have another Filter in your web application which does roughly the same job as the PrimeFaces file upload filter and is executed before the PrimeFaces file upload filter. For example, the MyFaces ExtensionsFilter which is bundled in Tomahawk. The request body can namely be parsed only once.

Upvotes: 2

Related Questions