保存使用angular-file-upload上传的文件

时间:2015-11-04 02:45:00

标签: angularjs servlets servlet-3.0

我创建了一个使用Angular File Upload组件(https://github.com/nervgh/angular-file-upload/wiki/Module-API)的页面,但是,我找不到如何获取上传的文件信息以将其保存在磁盘上。

我不知道关键名称是什么以及如何保存它。以下是我的代码示例,如果你能帮助我的话。

app.controller('HomeController', ['$scope', 'FileUploader', function ($scope, FileUploader) {
    $scope.uploadMessage = 'Arraste aqui o arquivo';

    var uploader = $scope.uploader = new FileUploader( { autoUpload: true, url: '/url'});

    // FILTERS

    uploader.filters.push({
        name: 'customFilter',
        fn: function(item /*{File|FileLikeObject}*/, options) {
            return this.queue.length <= 1;
        }
    });

    // Callbacks
    uploader.onAfterAddingFile = function (item) {
        $scope.uploadMessage = 'Enviando arquivo ' + item.file.name.toString();
    };

    uploader.onCompleteItem = function(item, response, status, headers) {

    };
}]);

我的servlet post函数就像这样:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

Angular组件帮助说有一个名为“alias”的属性{String}:包含该文件的字段的名称,默认为file。如果我使用request.getParameter(“file”)则为null。

更新

我在服务器中使用@MultipartConfig注释,但request.getPart始终为null。

1 个答案:

答案 0 :(得分:0)

需要更改您的网址,它应该是唯一的。 试试这个

var uploader = $scope.uploader = new FileUploader({ autoUpload: true, url: '/upload' });

服务器端:

@RequestMapping(value = "/upload" , method = RequestMethod.POST)
public void upload(HttpServletRequest request)
{
    //org.springframework.web.multipart.MultipartHttpServletRequest
    MultipartHttpServletRequest mRequest;
    mRequest = (MultipartHttpServletRequest) request;

    Iterator<String> itr = mRequest.getFileNames();
    while (itr.hasNext()) {
        //org.springframework.web.multipart.MultipartFile
        MultipartFile mFile = mRequest.getFile(itr.next());
        String fileName = mFile.getOriginalFilename();
        System.out.println("*****"+ fileName);

        //To copy the file to a specific location in machine.
        File file = new File('path/to/new/location');
        FileCopyUtils.copy(mFile.getBytes(), file); //This will copy the file to the specific location.
    }
}