how to upload a multipart file using angular js spring mvc

后端 未结 2 858
星月不相逢
星月不相逢 2020-12-19 01:27

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

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

    

        
2条回答
  •  情歌与酒
    2020-12-19 01:55

    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 = "/continueFileUpload";
     fileUpload.uploadFileToUrl(file, uploadUrl).then(function(result){
     $scope.errors = fileUpload.getResponse();
     console.log($scope.errors);
     $scope.errVisibility = true;
     }, function(error) {
     alert('error');
     })
    
    };
     }]);
    

    HTML:

    × Errors! {{errors.data.value}}

    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

    Really a good one for file upload.

提交回复
热议问题