在Spring MVC中使用不带表单的Multipart

时间:2015-08-02 17:39:30

标签: javascript angularjs spring spring-mvc multipart

我在stackoverflow中经历了很多关于这个特定主题的文章,经过详细分析后我终于敢于就同一主题发表另一个问题了。

我认为这显然是我想在这里做的,

我想要什么?

我想上传文件。我正在使用angularjs和Spring MVC。

来源:

Controller @Spring:

@RequestMapping(value="/upload", method=RequestMethod.POST, consumes = {"multipart/form-data"})
public String handleFileUpload(@RequestParam(value = "file") MultipartFile file){
    String name="";
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + "!";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}
@Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(500000000);
        return multipartResolver;
    }

HTML:

File to upload: <input type="file"
            file-model="file" name="fd"><br /> Name: <input type="text" name="name"><br />
        <br /> <input type="submit" ng-click="uploadFile()" value="Upload"> Press here to
        upload the file!

JS:

$scope.uploadFile = function() {
    var fd = new FormData();
    var file = $scope.file;
    fd.append('file', file);
    $http.post("/upload",fd,
            {
                headers : {
                    'Content-Type' : undefined
                }
            }).success(function(data) {
        debugger;
    }).error(function(data) {
        debugger;
    })
}

看起来很公平???以下是观察结果

执行意见:

enter image description here

enter image description here

参考文献:

Spring MVC - AngularJS - File Upload - org.apache.commons.fileupload.FileUploadException

Javascript: Uploading a file... without a file

What is the boundary parameter in an HTTP multi-part (POST) Request?

还有更多.... :)

更新

用于角度的指令

myApp.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });
        }
    }
}]);

从Chrome提取的请求:

enter image description here

2 个答案:

答案 0 :(得分:4)

我的方法存在问题:

我为MultiPartResolver创建了一个bean。解决问题后我的理解就像你只想在特定类型的文件或特定于应用程序的东西时定义这个bean。虽然我寻求更深入地了解这一点,并希望听到堆栈溢出的技术人员。

当前问题的解决方案:

我会提供我的源代码,

HTML:

<div ng-controller="myCtrl">
        <input type="file" file-model="myFile" />
        <button ng-click="uploadFile()">upload me</button>
    </div>

AngularJS:

     var myApp = angular.module('myApp', []);

        myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function(scope, element, attrs) {
                    var model = $parse(attrs.fileModel);
                    var modelSetter = model.assign;

                    element.bind('change', function(){
                        scope.$apply(function(){
                            modelSetter(scope, element[0].files[0]);
                        });
                    });
                }
            };
        }]);
        myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){

            $scope.uploadFile = function(){
                var file = $scope.myFile;
                var fd = new FormData();
                fd.append('file', file);
    //We can send anything in name parameter, 
//it is hard coded to abc as it is irrelavant in this case.
                var uploadUrl = "/upload?name=abc";
                $http.post(uploadUrl, fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                })
                .success(function(){
                })
                .error(function(){
                });
            }

        }]);

春天:

@RequestMapping(value="/upload", method=RequestMethod.POST)
    public String handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

和@arahant尽管我们在发送请求时没有在请求有效负载中看到任何文档base64内容,但angular确实发送了MultiPartFile,这里是截图

enter image description here

感谢所有参考。如果不是这些人,我根本不会解决这个问题。

参考文献:

http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

答案 1 :(得分:1)

在这里使用MultipartHttpServletRequest是一个简单的选项,无需任何其他更改即可使用。

public String handleFileUpload(MultipartHttpServletRequest request) {
    Map<String, MultipartFile> uploadedFiles = request.getFileMap();
    //...
}