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

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

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

    <mvc:annotation-driven />

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

我的表单看起来像这样:

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

};

弹簧控制器:

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

当我为头添加多部分/表单数据时,我得到**the request was rejected because no multipart boundary was found**异常

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


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

};

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

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

}]);

控制器

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

<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>

只要检查下面的链接,让你知道如何从头开始使用它,如果你对angularjs中的指令不熟悉的话。 使用AngularJS进行Spring MVC文件上传

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

链接地址: http://www.djcxy.com/p/48713.html

上一篇: how to upload a multipart file using angular js spring mvc

下一篇: Can a RestTemplate consume multipart/mixed?