Vendetta
Vendetta

Reputation: 294

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

Upvotes: 1

Views: 2118

Answers (1)

Pere Villega
Pere Villega

Reputation: 16439

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

The reasoning is that you get a NullPointerException when calling a method in body. bodyis 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 GETrequest.

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

Upvotes: 2

Related Questions