使用AngularJS和Spring MVC的jQuery Fileupload(Blueimp)

jQuery Fileupload (Blueimp) with AngularJS and Spring MVC

本文关键字:Fileupload Blueimp jQuery AngularJS Spring MVC 使用      更新时间:2023-09-26

我是web开发的新手,目前正在尝试实现一个简单的文件上传以进行测试。

总之,我的目标只是复制以下内容:http://blueimp.github.io/jQuery-File-Upload/angularjs.htmlJava服务器端。

使用jQueryFileupload插件和AngularJS,我想制作一个在服务器上上传文件的UI。在服务器端,我使用Java和SpringMVC来处理HTTP请求。

然而,我目前无法让它发挥作用,当然是因为我不知道在使用AngularJS的jQuery Fileupload时应该处理什么样的HTTP请求,而Blueimp文档对我没有帮助(可能是我的错,当你使用这种框架时,这可能是众所周知的)。

这是我当前的AngularJS控制器文件(它基本上是AngularJS示例的副本):

/* jshint nomen:false */
/* global window, angular */
(function () {
    'use strict';
    var url = '/ExerciseValidator/upload/';
    angular.module('file-upload', ['blueimp.fileupload'])
        .config([
            '$httpProvider', 'fileUploadProvider',
            function ($httpProvider, fileUploadProvider) {
                delete $httpProvider.defaults.headers.common['X-Requested-With'];
                fileUploadProvider.defaults.redirect = window.location.href.replace(
                    /'/[^'/]*$/,
                    '/cors/result.html?%s'
                );
                angular.extend(fileUploadProvider.defaults, {
                    // Enable image resizing, except for Android and Opera,
                    // which actually support image resizing, but fail to
                    // send Blob objects via XHR requests:
                    disableImageResize: /Android(?!.*Chrome)|Opera/
                        .test(window.navigator.userAgent),
                    maxFileSize: 999000,
                    acceptFileTypes: /('.|'/)(c|cpp|h|hpp)$/i
                });
            }
        ])
        .controller('FileUploadController', [
            '$scope', '$http', '$filter', '$window',
            function ($scope, $http) {
                $scope.options = {
                    url: url
                };
                $scope.loadingFiles = true;
                $http.get(url)
                    .then(
                        function (response) {
                            $scope.loadingFiles = false;
                            $scope.queue = response.data.files || [];
                        },
                        function () {
                            $scope.loadingFiles = false;
                        }
                    );
            }
        ])
        .controller('FileDestroyController', [
            '$scope', '$http',
            function ($scope, $http) {
                var file = $scope.file,
                    state;
                if (file.url) {
                    file.$state = function () {
                        return state;
                    };
                    file.$destroy = function () {
                        state = 'pending';
                        return $http({
                            url: file.deleteUrl,
                            method: file.deleteType
                        }).then(
                            function () {
                                state = 'resolved';
                                $scope.clear(file);
                            },
                            function () {
                                state = 'rejected';
                            }
                        );
                    };
                } else if (!file.$cancel && !file._index) {
                    file.$cancel = function () {
                        $scope.clear(file);
                    };
                }
            }
        ]);
}());

在我看来,我有一个包含data-ng-app="file-upload"data-ng-controller="FileUploadController"的表单。

这是我目前的Spring控制器:

@Controller
public class ExerciseValidatorController {
private static final String OUTPUT_FILEPATH = "D:/tmp/";
private final LinkedList<FileMeta> files = new LinkedList<>();
/**
 * Called on index page, returns the file upload page
 * @return the file upload page
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showExerciseValidator() {
    return "FileUploadView";
}
/**
 * Called when files are uploaded, write them to disk and call the validation page
 * @param request the request
 * @param response the response
 * @return TBD
 */
@RequestMapping(value="/upload/", method = RequestMethod.POST)
public @ResponseBody
LinkedList<FileMeta> postUpload(HttpServletRequest request, HttpServletResponse response) {
    if(!(request instanceof MultipartHttpServletRequest)) {
        return null;
    }
    Iterator<String> itr = ((MultipartHttpServletRequest)request).getFileNames();
    MultipartFile mpf = null;
    while (itr.hasNext()) {
        mpf = ((MultipartHttpServletRequest)request).getFile(itr.next());
        final FileMeta fileMeta = new FileMeta();
        fileMeta.setFileName(mpf.getOriginalFilename());
        fileMeta.setFileSize(mpf.getSize() / 1024 + " kB");
        fileMeta.setFileType(mpf.getContentType());
        try {
            fileMeta.setBytes(mpf.getBytes());
            FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(OUTPUT_FILEPATH + mpf.getOriginalFilename()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        files.add(fileMeta);
    }
    return files;
}
}

当我使用Firebug测试我的视图时,我得到以下错误:"NetworkError:405方法不允许-http://localhost:8080/ExerciseValidator/upload/"

当我尝试上传文件时,什么都不会发生:我可以在硬盘驱动器中选择一个文件,但它不会显示在可以上传的文件列表中。

我还尝试在我的Spring控制器中的/upload/上为GET方法添加一个处理程序。但是,即使它消除了405错误,我也不知道该如何处理这个请求。此外,我没有注意到UI有任何改进:可上传文件的列表没有显示。

有人知道我该怎么办吗?

在Javascript文件中,控制器的名称是FileUploadController,但该控制器的名称已经在jquery.fileupload-angular.js中定义。将其更改为InternalFileUploadController(例如)解决了问题。