Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to upload a multipart file using angular js spring mvc

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

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

    <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

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

like image 830
jos Avatar asked May 22 '14 14:05

jos


2 Answers

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

};
like image 180
jos Avatar answered Nov 20 '22 02:11

jos


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:

<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

Really a good one for file upload.

like image 21
Vishal Srinivasan Avatar answered Nov 20 '22 02:11

Vishal Srinivasan