简体   繁体   中英

NullPointerException: null playframework 2.1.1 file upload

i am just new-ish in play framework, I was Trying to code upload file with playframework 2.1.1, but I am getting this exception [NullPointerException]: null
I have following code in My Controller and using this link

package controllers;

//import com.ning.http.client.FilePart;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import play.*;
import play.mvc.*;
import play.data.*;
import static play.data.Form.*;
import java.io.File;
import models.*;
import views.html.*;

public class Application extends Controller {

    public static Result index() {
        return ok(index.render("My App"));
    }
public static Result upload(){
    MultipartFormData body=request().body().asMultipartFormData();
    MultipartFormData.FilePart picture=body.getFile("picture");//Error is here 

    if(picture!=null){
        //String fileName=picture.getFileName(); and if I uncomment this line it also show an error for 'value not find 'getFileName' ' is there any import is needed?
        String contentType=picture.getContentType();
        File file=picture.getFile();
        return ok("File Uploaded");
    }
    else 
    {
        flash("error", "Missing File");
        return redirect(routes.Application.index());
    }
//File file = request().body().asRaw().asFile();
//return ok("File uploaded");

}  

}

and following code in View that is app/views/upload.scala.html

@helper.form(action = routes.Application.upload, 'enctype -> "multipart/form-data") {

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

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

}

please give some suggestion that where i am wrong.

Thanks in Advance

You didn't post the routes file, but by the error I guess that you are mapping the request to a GET instead of POST .

The reasoning is that you get a NullPointerException when calling a method in body . body is initialized in the previous line from the request object, retrieving the contents as multipartFormData .

Your form snippet properly declares the form as multipart/form-data and maps to the controller's method as expected. This means that the only reason why you shouldn't get the contents is that the request has an empty body, and in this scenario that would only be in a GET request.

Of course, there may be a more exotic reason, but I bet that's the one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM