Java 如何使用angular js spring mvc上传多部分文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23810352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:19:06  来源:igfitidea点击:

how to upload a multipart file using angular js spring mvc

javaspringangularjsspring-mvc

提问by jos

I am trying to upload a file using angularjs and spring MVC

我正在尝试使用 angularjs 和 spring MVC 上传文件

I have a multipartResolver bean in application-context.xml.

我在 application-context.xml 中有一个 multipartResolver bean。

    <mvc:annotation-driven />

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="2097152" />
    </bean>

my form look like this:

我的表格是这样的:

<form method="post" id="fromFileUpload" enctype="multipart/form-data"
                ng-submit="continueFileUpload()">
        <div class="form-group">
            <label class="control-label col-sm-4 col-xs-12" for="quoteIdentifier">Quote Identifier : </label>
                <div class="col-xs-4 input-max">
                    <select type="text" class="form-control " name="quoteIdentifier" id="quoteIdentifier" ng-model="quoteIdentifier" ng-options="">
                    <option style="display: none" value="">Choose</option>
                    </select>
                </div>
                </div>
        <div class="form-group">
            <label class="control-label col-sm-4 col-xs-12" for="file">Please upload the file : <span class="required">*</span> </label>
            <div class="col-xs-4 input-max controls ">
                <input class="inline-block" type="file" name="file" ng-model="file" data-rule-required="true" id="file"         accept=".csv,.xsl,.xml,.mpp,application/vnd.ms-excel">
            </div>
            <span id="vaildFile" class="text-success icon-ok hide">Valid File</span> <span id="invaildFile" class="text-error icon-remove hide"> Invalid File</span>
        </div>
        <div class="box-header">
            <div class="actions">   
            <button type="submit" class="btn btn-primary">
                <i class="icon-arrow-right"></i> Continue
            </button>           
                </div>
        </div>    
</form>

$scope.continueFileUpload=function (){
var uploadUrl=serverUrl+"continueFileUpload";
var formData=new FormData();
formData.append("file",file.files[0]);
 $http({
        method: 'POST',
        url: uploadUrl,
        headers: {'Content-Type': false},
        data: formData,
        transformRequest: function(data, headersGetterFunction) {
                        return data;
         }
     })
    .success(function(data, status) {   
                    alert("success");
     })

};

spring controller:

弹簧控制器:

@Controller
public class FileUploadController {
@RequestMapping(value = "/continueFileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String continueFileUpload(HttpServletRequest request,
            HttpServletResponse response){
     MultipartHttpServletRequest mRequest;
        try {
            mRequest = (MultipartHttpServletRequest) request;
            mRequest.getParameterMap();

            Iterator<String> itr = mRequest.getFileNames();
            while (itr.hasNext()) {
                MultipartFile mFile = mRequest.getFile(itr.next());
                String fileName = mFile.getOriginalFilename();
                System.out.println(fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
return null;
    }

When I add multipart/form-data for the header I get **the request was rejected because no multipart boundary was found**exceptions

当我为标题添加 multipart/form-data 时,我得到**the request was rejected because no multipart boundary was found**异常

If I didnt add I get org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest

如果我没有添加我得到 org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest

采纳答案by jos

$scope.continueFileUpload=function (){
var uploadUrl=serverUrl+"continueFileUpload";
var formData=new FormData();
formData.append("file",file.files[0]);
 $http({
        method: 'POST',
        url: uploadUrl,
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function(data, headersGetterFunction) {
                        return data;
         }
     })
    .success(function(data, status) {   
                    alert("success");
     })

};

回答by Vishal Srinivasan

Creating a directive will be the most useful way in this. The following directive can be used.

创建指令将是最有用的方法。可以使用以下指令。

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

Service:

服务:

myApp.service('fileUpload', ['$q','$http', function ($q,$http) {
var deffered = $q.defer();
var responseData;
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
 headers: { 'Content-Type' : undefined}
})
.success(function(response){

/* $scope.errors = response.data.value; */


console.log(response);
 responseData = response;
 deffered.resolve(response);
 return deffered.promise;
 })
 .error(function(error){
 deffered.reject(error);
 return deffered.promise;
 });

}

this.getResponse = function() {
 return responseData;
 }

}]);

Controller:

控制器

myApp.controller('myCtrl', ['$scope', '$q', 'fileUpload', function($scope, $q, fileUpload){
 $scope.dataUpload = true;
 $scope.errVisibility = false;
 $scope.uploadFile = function(){
 var file = $scope.myFile;
 console.log('file is ' );
 console.dir(file);

var uploadUrl = "<give-your-url>/continueFileUpload";
 fileUpload.uploadFileToUrl(file, uploadUrl).then(function(result){
 $scope.errors = fileUpload.getResponse();
 console.log($scope.errors);
 $scope.errVisibility = true;
 }, function(error) {
 alert('error');
 })

};
 }]);

HTML:

HTML:

<div ng-controller = "myCtrl">
    <div class="jumbotron">
    <input type="file" file-model="myFile"/>
    <button ng-click="uploadFile()">upload me</button>
</div>
                <div ng-show="errVisibility" class="alert alert-danger fade in">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                <strong>Errors!</strong> {{errors.data.value}}
                </div>
</div>

Just check this following link that let you know how to use this from scratch if you are new to directives in angularjs. Spring MVC file upload using AngularJS

如果您不熟悉 angularjs 中的指令,请查看以下链接,让您知道如何从头开始使用它。 使用AngularJS上传Spring MVC文件

Really a good one for file upload.

真的是一个很好的文件上传。