您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我的方法存在问题:

我为MultiPartResolver创建了一个bean。解决问题后的理解是,仅当你需要特定类型的文件或非常特定于应用程序的文件时,才定义此bean。尽管我希望对此有更多了解,并希望能从stackoverflow的技术人员那里听到。

当前问题的解决方案:

我会给出我的源代码

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

        }]);

spring:

@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

Java 2022/1/1 18:15:49 有480人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶