在 Spring MVC 中使用 Multipart without Form

Kir*_*shi 5 javascript spring spring-mvc multipart angularjs

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

我认为我想在这里做的事情很明显,

我想要什么?

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

来源 :

控制器@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;
    }
Run Code Online (Sandbox Code Playgroud)

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!
Run Code Online (Sandbox Code Playgroud)

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;
    })
}
Run Code Online (Sandbox Code Playgroud)

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

执行观察:

在此处输入图片说明

在此处输入图片说明

参考 :

Spring MVC - AngularJS - 文件上传 - org.apache.commons.fileupload.FileUploadException

Javascript:上传文件...没有文件

HTTP 多部分 (POST) 请求中的边界参数是什么?

还有很多....:)


更新

用于角度的指令,

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]);
            });
        }
    }
}]);
Run Code Online (Sandbox Code Playgroud)

从 chrome 中提取的请求:

在此处输入图片说明

Kir*_*shi 4

我的方法存在问题:

我为 MultiPartResolver 创建了一个 bean。解决问题后我的理解是,只有当您需要特定类型的文件或特定于应用程序的文件时,才定义此 bean。尽管我寻求对此有更多的了解,并且很想听到 stackoverflow 技术人员的意见。

当前问题的解决方案:

我会给出我的源代码,

HTML:

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

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(){
                });
            }

        }]);
Run Code Online (Sandbox Code Playgroud)

春天 :

@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.";
        }
    }
Run Code Online (Sandbox Code Playgroud)

@arahant即使我们在发送请求时没有在请求负载中看到任何文档base64内容,Angular确实发送了MultiPartFile,这是屏幕截图

在此输入图像描述

感谢所有参考文献。如果没有这些人,我根本就解决不了这个问题。

参考 :

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