Uploading an empty file automatically results in an NPE
-
25-09-2019 - |
Question
I'm a bit of a newbie to the Play Framework, but I don't see any documentation on how to approach this. Basically I've got a form to upload a text file to the server, here's the relevant snippet:
#{form @Sprockets.upload() , enctype:'multipart/form-data' }
<input type="file" name="sprocketFile" size="chars" />
<input type="submit" value="Submit Sprocket" />
#{/form}
On the controller side, here's the upload method:
public static void upload(File sprocketFile) {
}
My issue is that if the user doesn't bother populating the form and just hits "Submit Sprocket", Play automagically generates an NPE as it tries to convert the form data to a file. How I can work around this? This happens even before the controller validation code kicks in, so simply throwing in a @Required doesn't help:
@64m30kf1p
Internal Server Error (500) for request POST /sprockets/upload
Oops: NullPointerException
An unexpected error occured caused by exception NullPointerException: null
play.exceptions.UnexpectedException: Errors serializationProblem
at play.data.validation.ValidationPlugin.save(ValidationPlugin.java:146)
at play.data.validation.ValidationPlugin.onActionInvocationResult(ValidationPlugin.java:65)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:293)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.NullPointerException
at play.data.validation.ValidationPlugin.save(ValidationPlugin.java:136)
... 3 more
My end goal is to show a pretty error message back to the user, but Play is preventing me from doing this. This is with Play 1.1 on OS X if it makes a difference.
Solution 3
I've found the source of the problem, and it's my own fault. The issue at hand is naturally part of the source I didn't include in the original question. Here's the sample code:
public static void upload(@Required File sprocketFile) {
try {
if (sprocketFile == null || validation.hasErrors()) {
validation.addError("Upload Error", "Please select a sprocket to upload", sprocketFile);
params.flash();
validation.keep();
index();
}
The issue was using the sprocketFile as the last parameter in validation.addError(). I discovered this while running the app in debug mode in NetBeans. Thanks for your help @niels.
OTHER TIPS
Possible workaround would be an @Before-Interceptor. There you can check the paramter and redirect to an error page. This should work. Please create a ticket at http://play.lighthouseapp.com with a small example application.
You form and controller do not match
<input type="file" name="sprocketFile" size="chars" />
Says you are uploading a File object to a variable named sprocketFile
But, your code says you are storing in an object named licenceFile
public static void upload(File licenseFile) {
Try making the two match.