如何在由angularJs发送的PlayFramework控制器中获取文件?

时间:2016-01-25 12:28:49

标签: angularjs playframework

我目前正在使用angularJs在PlayFramework中处理文件上传。当我调用上传功能时,我收到了400个错误的请求响应。

下面是我的angularJs和Controller代码。 注意:当我的控制器(操作)内部没有实现时,我能够得到200响应。

 $scope.uploadFile = function () {
                $scope.upload($scope.bonus_file, baseURL + 'controller/upload_file');
            };

            // upload on file select or drop
            $scope.upload = function (file, path) {
                alert('Hello');
                Upload.upload({
                    url: path,
                    data: {file: file}
                }).then(function (resp) {
                    if (resp.data.status == 'success') {
                        sweetAlert("Done!", resp.data.message, "success");
                        $scope.bonus_file = '';
                        $scope.salary_file = '';
                    } else {
                        sweetAlert("Oops...", resp.data.message, "error");
                        $scope.bonus_file = '';
                        $scope.salary_file = '';
                    }
                }, function (evt) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
                });
            };



public Result uploadFile() {
        play.mvc.Http.MultipartFormData body = request().body().asMultipartFormData();
        play.mvc.Http.MultipartFormData.FilePart picture = body.getFile("file");
        try {
            if (picture != null) {
                String fileName = picture.getFilename();
                String contentType = picture.getContentType();
                java.io.File file = picture.getFile();
                StorageHelper.uploadFile(file, fileName);
                return ok("File uploaded");
            } else {
                return badRequest();
            }
        } catch (Exception e) {
            System.out.println("Exception While Uploading File:" + e.getMessage());
            return ok("File uploaded Failed:" + e.getMessage());
        }
    }

1 个答案:

答案 0 :(得分:0)

根据Play's documentation

  

将文件发送到服务器的另一种方法是使用Ajax上传文件   从表单异步。在这种情况下,请求正文将不会   编码为multipart / form-data,但只包含普通文件   内容。

因此,你应该试试这个:

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