I'm using Play in Java and I have problem with Handling file upload.
I made everything like on this page but I get NullPointerException
when I submit the form.
Here is my form:
@form(action = routes.Application.upload, 'enctype -> "multipart/form-data") {
<input type="file" name="picture">
<p>
<input type="submit">
</p>
}
Route:
POST /upload controllers.Application.upload()
Here is my controller:
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart picture = body.getFile("picture"); //here i got NullPointerException
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
return ok("File uploaded");
} else {
flash("error", "Missing file");
return redirect(routes.Application.index());
}
}
I've tried couple of solutions found on the Internet but none of them helped me.
How can I fix it?
Keep in mind that
NullExceptions
in this place is forbody
not forpicture
The only possible reason is that you are sending it with HTML form which hasn't
enctype="multipart/form-data"
(maybe you didn't refresh the form in the browser and still trying to send a normal form?)make sure (in your browser), that page where you're filling the form has this form declaration and try again.