简体   繁体   中英

NullPointerException when passing the file instance to another method in Playframework

I am trying to upload a file with playframework. I create a form and corresponding controller as below :

<form action="@{Admin.testUpload()}" method="POST" enctype="multipart/form-data">
    <input type="text" name="title" />
    <input type="file" name="f1" />
    <input type="file" name="f2" />    
    <input type="submit" value="Send it..." />
</form>


public static void testUpload(File f1, File f2) { 
    System.out.println(f1.getName());
    System.out.println(f2.getName());
}

It is fine now, I can get the file by the instances f1 and f2. However, when I want to pass the file instance to another method, it will occur null pointer exception. Such as :

public static void testUpload(File f1, File f2) {
    test2(f1);
}

public static void test2(File f1) {
    System.out.println(f1.getName());
}

It will cause exception within test2 method. And I found the playframework try to GET the image from a tmp folder. It seems that playframework automatically upload the file to a tmp folder and create a folder with the file name that I uploaded.

Is it the play mechanism?

When you call a public static method in your controller, Play will perform an HTTP redirect, because it believes you are calling another action.

So when you are redirecting, the second file object doesn't exist. You have two options here.

Firstly, you can make test2 a non-public method.

Secondly, you can annotate the method with @Util , which tells Play that it is not an action, and therefore will not attempt to redirect.

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