Question

I'm building a web application with Struts2. There's a small part that involves File Upload. The File Upload works well. However a NullPointerException is thrown when I choose to NOT upload a file. The only way I can handle this in code, is by catch(NullPointerException NPE) . And a part of the code gets repeated. I wish to avoid this.

Is there any way I can handle a NULL for a file upload in Struts2?

My HTML file:

<s:file style="height:auto;width:550px;display:inline;align:center;" name="userImage" cssClass="text input" onchange="checkFile(this)"/>

My Java action code which handles this:

try{
String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);}

catch(NullPointerException NPE){//if I choose to NOT upload a file}
catch(Exception E){//some code}

I've tried the getUserImage()==null but it does not help. Do I absolutely have to handle the rest of the code inside the catch(NullPointerException NPE) block?

Was it helpful?

Solution

Most likely, the NullPointerException is thrown at one of the following two lines

File fileToCreate = new File(filePath, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);

because this.userImageFileName and/or this.userImage is null, if you do not upload a file.

So, try this:

if(this.userImageFileName != null && this.userImage != null){
   File fileToCreate = new File(filePath, this.userImageFileName);
   FileUtils.copyFile(this.userImage, fileToCreate);
}

Now, no NullPointerException should occure, since you checked for null in advance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top