Play 2.0.4 file upload. NullPointerException: null

2019-07-17 10:19发布

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?

1条回答
等我变得足够好
2楼-- · 2019-07-17 10:44

Keep in mind that NullExceptions in this place is for body not for picture

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.

<form action="/upload" method="POST" enctype="multipart/form-data">

    <input type="file" name="picture">

    <p>
        <input type="submit">
    </p>

</form>
查看更多
登录 后发表回答