4

我正在使用 Java Play Framework 和这个 File-Upload-Plugin:http ://blueimp.github.io/jQuery-File-Upload/ 。阅读文档http://www.playframework.com/documentation/2.0/JavaFileUpload后,我在我的 Java Play 控制器中使用了这个特定的代码。

public static Result upload() {
  File file = request().body().asRaw().asFile();
  return ok("File uploaded");
}

我还将这条路线添加到我的项目中:

POST    /upload                     controllers.Image.upload()

我的视图模板:

@(scripts: Html)

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" name="files[]" data-url="/upload">
@scripts
<script>
$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            data.context = $('<p/>').text('Uploading...').appendTo(document.body);
            data.submit();
        },
        done: function (e, data) {
            data.context.text('Upload finished.');
        }
    });
});
</script>
</body> 

现在,如果我上传图片,萤火虫会显示以下错误:

"NetworkError: 500 Internal Server Error - http://localhost:9000/upload"

错误是由控制器上传操作中的这一行引起的:

  File file = request().body().asRaw().asFile();

有人知道解决方案吗?谢谢您的帮助。

4

2 回答 2

1

我猜你可以以不同的方式访问你的上传文件。你可以使用类似的东西:

    Http.MultipartFormData body = request().body().asMultipartFormData();

    for(Http.MultipartFormData.FilePart part : body.getFiles()){
        Logger.debug(part.getFilename());
        Logger.debug(part.getKey());
        Logger.debug(part.getContentType());
        Logger.debug(part.getFile().getName());
        Logger.debug(part.getFile().getAbsolutePath());
        Logger.debug(String.valueOf(part.getFile().getTotalSpace()));
    }

一个你有你的 java.io.File 实例你可以做任何你想做的事

于 2013-12-08T23:19:41.273 回答
0

实际上,这是我的控制器部分,通过它我可以将文件从我的临时文件夹移动到应用程序公用文件夹,以便我可以进一步使用它。json 将作为多部分表单数据返回。所以我们必须像这样使用。希望这能解决您的问题。

MultipartFormData body = request().body().asMultipartFormData();
        FilePart picture = body.getFile("file");
            if (picture != null) {
                File tempimg = picture.getFile();
                Path temp = tempimg.toPath();
                Path newFile = new File(Play.application().path().getAbsolutePath()+"/public/uploaded",picture.getFilename()).toPath();
                Files.move(temp, newFile);
                return ok("File uploaded");
            } else {
                flash("error", "Missing file");
                return badRequest("File Missing");    
            }
于 2014-05-29T20:30:15.980 回答