2

请帮我寻找在 Play Framework 2 (Java) 中上传多个文件的示例。

我试试这段代码:

public static Result saveImages() {
    File dir = new File(Play.application().path() + File.separator + "public" + File.separator + "uploads");
    if (!dir.exists()) {
        dir.mkdirs();
    }
    FileOutputStream moveTo = null;
    String filename = request().headers().get("x-file-name").toString();
    Logger.info("Name of the file " + filename);
    return ok();
}

在我看来 :

    <form action="save_image" method="POST" enctype="multipart/form-data">
        <input type="file" name="image" />
        <input type="submit" value="save">
    </form>

但是这段代码给了我一个错误NullPointerException

String filename = request().headers().get("x-file-name").toString();

堆栈跟踪 :

[error] application - 

! @6dkiaiban - Internal server error, for (POST) [/save_image] ->

 play.api.Application$$anon$1: Execution exception[[NullPointerException: null]]
at play.api.Application$class.handleError(Application.scala:289) ~[play_2.10.jar:2.1.0]
at play.api.DefaultApplication.handleError(Application.scala:383) [play_2.10.jar:2.1.0]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anon$2$$anonfun$handle$1.apply(PlayDefaultUpstreamHandler.scala:132) [play_2.10.jar:2.1.0]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anon$2$$anonfun$handle$1.apply(PlayDefaultUpstreamHandler.scala:128) [play_2.10.jar:2.1.0]
at play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113) [play_2.10.jar:2.1.0]
at play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113) [play_2.10.jar:2.1.0]
 java.lang.NullPointerException: null
at controllers.Realty.saveImages(Realty.java:76) ~[na:na]
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$9$$anonfun$apply$9.apply(routes_routing.scala:253) ~[na:na]
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$9$$anonfun$apply$9.apply(routes_routing.scala:253) ~[na:na]
at play.core.Router$HandlerInvoker$$anon$6$$anon$2.invocation(Router.scala:141) ~[play_2.10.jar:2.1.0]
at play.core.Router$Routes$$anon$1.invocation(Router.scala:322) ~[play_2.10.jar:2.1.0]
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:31) ~[play_2.10.jar:2.1.0]
4

1 回答 1

0

如果有人正在寻找一种从 POST 请求中提取文件的方法,以下对我有用:

(输入的属性名称设置为“jsonFile”)

Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart resourceFile = body.getFile("jsonFile");

if( resourceFile != null )
{
    File uploadedFile = resourceFile.getFile();
}

编辑:编辑以供参考,因为我刚刚注意到这个问题相当古老

于 2013-05-21T15:03:18.100 回答