File upload using angularJS and Spring MVC Example

 

Angular JS Section :

  1. Angular Controller
$scope.submitUser = function(isValid) {

var file = $scope.myFile;
/* console.log('file is ' );
console.dir(file);*/
var uploadUrl = "user/saveUserDataAndFile";
var fd = new FormData();
fd.append('file', file);
fd.append('user',angular.toJson($scope.user,true));
console.log('Socpe of user'+$scope.user);
$http.post(uploadUrl, fd, {
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
}).success(function() {
console.log('success');
}).error(function() {
console.log('error');
});
}

2. Front End Form :

<form name="userForm" ng-submit="submitUser(userForm.$valid)" novalidate>
 <input type="hidden" ng-model="user.id" name="id">
 <div class="row">
 <div class="col-lg-6">
 <div class="row" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
 <div class="col-lg-12">
 <input class="form-control" placeholder="Username" type="text"
 ng-model="user.username" ng-minlength="3" name="username" required />
 <p ng-show="userForm.username.$invalid && !userForm.username.$pristine" class="help-block"> required.</p>
 <p ng-show="userForm.username.$error.minlength" class="help-block">Too short.</p>
 <p ng-show="userForm.username.$error.maxlength" class="help-block">Too long.</p>
 <br /> 
 
 <input class="form-control"
 placeholder="Enter Password" type="password"
 ng-model="user.password" ng-minlength="5" name="password" required />
 <p ng-show="userForm.password.$invalid && !userForm.password.$pristine" class="help-block">Password is required.</p>
 <br />
 
 <p ng-show="userForm.password.$error.minlength" class="help-block">Too short.</p>
 <p ng-show="userForm.password.$error.maxlength" class="help-block">Too long.</p>
 </div>
 </div>

 <div class="row">
 <div class="col-lg-12">
 <input type="text" name="role"
 ng-model="user.role" class="form-control" disabled/><br />
 </div>
 </div>

 <div class="row">
 <div class="col-lg-12">
 <input class="form-control" placeholder="FirstName" type="text"
 ng-model="user.member.firstName" /><br /> <input
 class="form-control" placeholder="Enter Last name" type="text"
 ng-model="user.member.lastName" /><br />
 </div>
 </div>

 </div>
 <div class="col-lg-6">

 <div class="row">
 <div class="col-lg-12">
 <input class="form-control" placeholder="Email" type="text"
 ng-model="user.member.email" /><br />
 <input class="form-control" placeholder="Zip Code" type="text"
 ng-model="user.member.zipCode" /><br /> <input
 class="form-control" placeholder="Enter Phone Number"
 type="text" ng-model="user.member.phoneNumber" ng-pattern="/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/" /><br />
 </div>
 </div>
 <div class="row">
 <div class="col-lg-12">
 <input class="form-control" placeholder="Address line 1"
 type="text" ng-model="user.member.addressLine1" /><br /> <input
 class="form-control" placeholder="Address Line 2" type="text"
 ng-model="user.member.addressLine2" /><br />
 </div>
 </div>
 
 <div class="row">
 <div class="col-lg-12">
 <input type="file" file-model="myFile"/>
 </div>
 </div>


 </div>


 </div>
 <div class="row">
 <div class="col-lg-12">

 <button type="btn btn-primary submit" class="btn btn-lg btn-primary"
 ng-hide="userForm.$invalid">Save</button>
 
 </form>

3. Directive :

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

Back End Side Spring MVC:

1. Rest Controller

@RequestMapping(value = "/user/saveUserDataAndFile", method = RequestMethod.POST)
	@ResponseBody
	public Object saveUserDataAndFile( @RequestParam(value = "user") String userInfo,
	        @RequestParam(value = "file") MultipartFile file,HttpServletRequest request) {
		
		System.out.println("Inside File upload" + userInfo);
		ObjectMapper mapper = new ObjectMapper();
		try {
			Login login = mapper.readValue(userInfo, Login.class);
			 userService.addUser(login);
			System.out.println(login.toString());
		} catch (JsonParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JsonMappingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//String rootDirectory = request.getSession().getServletContext().getRealPath("/");
		String rootDirectory = "D:\\testUpload\\";
		System.out.println("Root Directory "+rootDirectory);
		try {
			file.transferTo(new File(rootDirectory  + file.getOriginalFilename()));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
	}

Login and Member DTO/MODEL:

package com.essential.project.dto;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
public class Login {
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	private String username;
	private String password;
	private String role;
	private int enabled;
	
	public int getEnabled() {
		return enabled;
	}
	public void setEnabled(int enabled) {
		this.enabled = enabled;
	}
	public Login(){
		
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Member getMember() {
		return member;
	}
	
	public void setMember(Member member) {
		this.member = member;
	}
	
	
	@OneToOne(cascade=CascadeType.ALL)
	private Member member;
	
	@JsonIgnore
	@OneToMany(cascade=CascadeType.ALL,fetch = FetchType.LAZY)
	private List expenses;
	
	
	
	public List getExpenses() {
		return expenses;
	}
	public void setExpenses(List expenses) {
		this.expenses = expenses;
	}
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	
	
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
}

Member DTO:

package com.essential.project.dto;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="member")
public class Member {
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	public Member(){
		
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getDateOfBirth() {
		return dateOfBirth;
	}
	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
	public String getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
	private String firstName;
	private String lastName;
	private String email;
	private Date dateOfBirth;
	private int status;
	private String phoneNumber;
	private String addressLine1;
	private String addressLine2;
	private String userImage;

	private String zipCode;

	public String getZipCode() {
		return zipCode;
	}

	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

	public String getUserImage() {
		return userImage;
	}

	public void setUserImage(String userImage) {
		this.userImage = userImage;
	}

	public String getAddressLine1() {
		return addressLine1;
	}

	public void setAddressLine1(String addressLine1) {
		this.addressLine1 = addressLine1;
	}

	public String getAddressLine2() {
		return addressLine2;
	}

	public void setAddressLine2(String addressLine2) {
		this.addressLine2 = addressLine2;
	}
}

Services and repository are not shown . If you need the full example of the file upload using Angular js and Spring MVC . Please comment with email id or send me your email id at anandgodar@gmail.com. Please don’t forget to put the comment on the article.

SHARE TO DOWNLOAD

Enjoy