在 Spring MVC 中使用 Multipart without Form [英] Using Multipart without Form in Spring MVC

查看:27
本文介绍了在 Spring MVC 中使用 Multipart without Form的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想要什么?

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

来源:

控制器@Spring :

@RequestMapping(value="/upload", method=RequestMethod.POST,consumes = {"multipart/form-data"})public String handleFileUpload(@RequestParam(value = "file") MultipartFile file){字符串名称="";如果 (!file.isEmpty()) {尝试 {byte[] bytes = file.getBytes();BufferedOutputStream 流 =new BufferedOutputStream(new FileOutputStream(new File(name)));流.写(字节);流.关闭();return "您上传成功" + 名称 + "!";} 捕获(异常 e){return "你上传失败 " + 姓名 + " => " + e.getMessage();}} 别的 {返回您上传失败"+名称+因为文件是空的.";}}@豆角,扁豆公共 MultipartResolver multipartResolver() {CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();multipartResolver.setMaxUploadSize(500000000);返回 multipartResolver;}

HTML:

要上传的文件:

JS:

$scope.uploadFile = function() {var fd = new FormData();var 文件 = $scope.file;fd.append('文件', 文件);$http.post("/上传",fd,{标题:{内容类型":未定义}}).成功(功能(数据){调试器;}).错误(函数(数据){调试器;})}

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

对执行的观察:

参考资料:

解决方案

我的方法有问题:

我为 MultiPartResolver 创建了一个 bean.解决问题后,我的理解是,您仅在需要特定类型的文件或特定于应用程序的文件时才定义此 bean.虽然我希望对此有更多的了解,并且很想听听 stackoverflow 技术人员的意见.

当前问题的解决方案:

我会提供我的源代码,

HTML:

<input type="file" file-model="myFile"/><button ng-click="uploadFile()">上传我</button>

AngularJS:

 var myApp = angular.module('myApp', []);myApp.directive('fileModel', ['$parse', function ($parse) {返回 {限制:'A',链接:函数(范围,元素,属性){var 模型 = $parse(attrs.fileModel);var modelSetter = model.assign;element.bind('change', function(){范围.$应用(函数(){模型设置器(范围,元素[0].文件[0]);});});}};}]);myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){$scope.uploadFile = function(){var 文件 = $scope.myFile;var fd = new FormData();fd.append('文件', 文件);//我们可以在name参数中发送任何东西,//它被硬编码为 abc,因为在这种情况下它是无关紧要的.var uploadUrl = "/upload?name=abc";$http.post(uploadUrl, fd, {变换请求:angular.identity,标头:{'内容类型':未定义}}).成功(功能(){}).错误(功能(){});}}]);

春天:

@RequestMapping(value="/upload", method=RequestMethod.POST)public String handleFileUpload(@RequestParam("name") 字符串名称,@RequestParam("file") MultipartFile 文件){如果 (!file.isEmpty()) {尝试 {byte[] bytes = file.getBytes();BufferedOutputStream 流 =new BufferedOutputStream(new FileOutputStream(new File(name)));流.写(字节);流.关闭();return "您上传成功" + 名称 + "!";} 捕获(异常 e){return "你上传失败 " + 姓名 + " => " + e.getMessage();}} 别的 {返回您上传失败"+名称+因为文件是空的.";}}

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

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

参考资料:

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

I had gone through many articles in stackoverflow on this specific topic, after a detailed analysis I have finally dared to post another question on the same topic.

I think this would be obvious that what I wanted to do here,

What do I want?

I want to upload a file. I am using angularjs and Spring MVC.

Source :

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

Looks fair??? Here are the observations

Observations on execution:

References :

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?

And many more....:)


Update

Directive which is used in angular,

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]);
            });
        }
    }
}]);

Request extracted from chrome :

解决方案

Problem in my approach :

I created a bean for MultiPartResolver. My understanding after resolving the issue is like you define this bean only when you want a specific type of file or something very specific to the application. Although I seek more insight into this and would love to hear from techies of stackoverflow.

Solution for current problem:

I would give my source code,

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.";
        }
    }

And @arahant Even though we don't see any document base64 content in the request payload while sending request, angular does send MultiPartFile, here is the screenshot

Thanks to all the references. If not for these people I wouldn't have solved this problem at all.

References :

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

这篇关于在 Spring MVC 中使用 Multipart without Form的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆