0

I am learning to use JSF 2.2 and the upload file tag.

So I created a basis xhtml file to upload a file in a bean:

<h:form id="form" enctype="multipart/form-data">
    <h:inputFile id="file" value="#{fileupload.uploadedFile}" />

    <h:commandButton value="Upload" action="#{fileupload.saveFile}" />
</h:form>

Here is the associated backing-bean :

@ManagedBean
@ViewScoped
public class Fileupload {

    private Part uploadedFile; // getters + setters

    private String folder = "c:\\files";

    public void saveFile(){
        try (InputStream input = uploadedFile.getInputStream()) { // <-- Nullpointer here
            String fileName = uploadedFile.getSubmittedFileName();

            Files.copy(input, new File(folder, fileName).toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

As soon as I submit the form i have this error :

Caused by: java.lang.NullPointerException
at com.pro.beans.Fileupload.saveFile(Fileupload.java:30)

So my guess is that the uploadFile mutable is not set by the xhtml and so when I click on the button I got a NullpointerException, but I do understand why is it not set cause for me it is conform to all the tutorial I saw.

fuggerjaki61
  • 822
  • 1
  • 11
  • 24
Quentin M
  • 171
  • 2
  • 11
  • Instead of posting a whole stack trace as if you have no clue what exactly a NullPointerException is (and thus risking your question to be closed as a duplicate of https://stackoverflow.com/q/218384), can you please just tell which variable exactly is null where your code didn't expect that? – BalusC Jun 05 '20 at 22:55
  • Hi, thx for your feedback I edited my question. – Quentin M Jun 06 '20 at 07:31
  • Hi, BalusC is right, you should be more explicit. Effectively your question is very much related to https://stackoverflow.com/questions/8875818/how-to-use-primefaces-pfileupload-listener-method-is-never-invoked-or-uploaded. Read the code parts after '3', especially the **_'Save it, now'_** part and the last paragraph before the 'PrimeFaces 8.x' part. – Kukeltje Jun 06 '20 at 14:54
  • My question is a duplication from : https://stackoverflow.com/questions/35342502/jsf-2-2-file-upload-return-java-lang-nullpointerexception It solved my issue. – Quentin M Jun 08 '20 at 06:15

1 Answers1

-1

I there,

public Part getFile() {
    return file;
}

public void setFile(Part file) {
    this.file = file;
}
Carlos Maemo
  • 91
  • 1
  • 9