0

I am uploading file in JSF and it is always null so that I get a NullPointerException.

My backingBean:

@ManagedBean
@SessionScoped
public class UploadFile implements Serializable {
    private Part fileUp;

    public String processFileUpload() throws IOException {
        Part uploadedFile = getFileUp();

        final Path destination = Paths.get("c:/temp/" + FilenameUtils.getName(getSubmittedFileName(uploadedFile)));

        InputStream bytes = null;

        if (null != uploadedFile) {

            bytes = uploadedFile.getInputStream();  //Copies bytes to destination.
            Files.copy(bytes, destination);
        }

        return "success";
    }

    public Part getFileUp() {
        return fileUp;
    }

    public void setFileUp(Part fileUp) {
        this.fileUp = fileUp;
    }

My front page:

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

    <h:outputLabel for="fu" value="Name:" />
    <h:inputFile id="fu" value="#{uploadFile.fileUp}">
    </h:inputFile>
    <p>
        <h:messages id="messagesUpload" />
    </p>

    <h:commandButton value="Upload File" action="#{uploadFile.processFileUpload}">
        <f:ajax execute="fileUpload" render="@all" />
    </h:commandButton>
</h:form>

Could anyone please help me set the file to its value and tell me why it's getting the null value?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
user_24434
  • 87
  • 8
  • Off-topic: http://stackoverflow.com/questions/7415230/uiform-with-prependid-false-breaks-fajax-render – Kukeltje Feb 15 '17 at 12:10

1 Answers1

0

Although the code you pasted seems incomplete, i suspect the error might be coming from

final Path destination = Paths.get("c:/temp/" + 
FilenameUtils.getName(getSubmittedFileName(uploadedFile)));

So try the code below. Also note, you type your c in "c:/temp/" in small letter. Is that a correct system path?

public void processUpload() {
    String path = "C:/temp/";
    try (InputStream input = fileUp.getInputStream()) {
        String fileName = fileUp.getSubmittedFileName();
        Files.copy(input, new File(path, fileName).toPath());
    } catch (IOException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }
}
Tunde Michael
  • 364
  • 4
  • 8