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.

 

Enjoy

AngularJS : Factory, Service and Provider with example

AngularJS Factory Example :

userApp.factory('userService', function($http) {
var self = this;
return {
getAllUsers : function() {
return $http.get('user/getAllUsers');
},
getUserById : function(id) {
return $http.get('user/getUserById/' + id);
},
addUser : function(userData) {

return $http.post('user/saveUser', userData);
},
deleteUser : function(id) {
return $http.get('user/deleteUser/' + id);
},
getUser : function(user) {
return $http.post('user/getUser', user);
}
}

});

AngularJS Service Example

userApp.service('myService', function () {
  this.name = '';
    this.setName = function (newName) {
     this.name = newName;
     return this.name;
   };
 });

AngularJS Provider Example
//defining provider

 app.provider('configurable', function () {
 var firstName = '';
 this.setName = function (firstName) {
      firstName= firstName;
 };
 this.$get = function () {
      return {
         name: firstName
       };
  };
 });
//configuring provider
 app.config(function (configurableProvider) {
 configurableProvider.setName("Saksham Chauhan");
 });

Difference between success and then in angularJS

  • success() returns the original promise
  • then() returns a new promise

The difference is then() drives sequential operations, since each call returns a new promise.

$http.get(/*...*/).
  then(function seqFunc1(response){/*...*/}).
  then(function seqFunc2(response){/*...*/})
  1. $http.get()
  2. seqFunc1()
  3. seqFunc2()

success() drives parallel operations, since handlers are chained on the same promise.

$http(/*...*/).
  success(function parFunc1(data){/*...*/}).
  success(function parFunc2(data){/*...*/})
  1. $http.get()
  2. parFunc1(), parFunc2() in parallel

Copied from Stackoverflow.

How i used :

then Example :

$scope.findAllUsers = function() {
$scope.loading = true;
userService.getAllUsers().then(function successCallback(data) {
$scope.loading = false;
$scope.userRecords = data.data;

});
}

Success Example:

$scope.findAllUsers = function() {
$scope.loading = true;
userService.getAllUsers().success(function(data) {
$scope.loading = false;
$scope.userRecords = data;

});
}

$cookieStore VS localStorage VS sessionStorage

AngularJS includes a service component inside ngCookies directive to storage objects in a key-value format called cookieStore. This storage differs from HTML5 APIs localStorage and sessionStorage.
$cookieStore:
– Session scoped.
– Not persistant, expires
– Automatic serialization or deserialization toJson/fromJson.
– Values are included in every server request.
– As any cookie, its size must be less than 4KB.

Example of $cookieStore

// Put cookie
  $cookieStore.put('cookieName','my-data');
  // Get cookie
  var favoriteCookie = $cookieStore.get('cookieName');
  // Removing a cookie
  $cookieStore.remove('cookieName');

localStorage:

  • Domain scoped.
  • Same data can be accessed and stored in a domain and can be shared between to tabs.
  • Persists when browser is closed. No expiration date.
  • Data stored locally without affecting website performance, more secure.
  • Data never transferred to the server.
  • Storage limit is larger (at least 5MB).
    Example:
// Store
 localStorage.setItem("name", "John");
 // Retrieve
 localStorage.getItem("name");

sessionStorage:

  • Session scoped
  • Data is lost when tab is closed
  • Data never transferred to the server.
  • Storage limit is larger (at least 5MB).
 // Store
 sessionStorage.setItem("name", "John");
 // Retrieve
 sessionStorage.getItem("name");

Angular JS and Spring MVC Integration Example

members

This example include the angular JS application integrated with Spring MVC and Hibernate.This application contains some unwanted files and models. Please see only the member side if you really want the angular and spring mvc extraction example.

Included features are :

  1. Angular JS Routing
  2. Agular JS Directive
  3. Angualr JS Service/Factory
  4. Angular JS Spring MVC integration
  5. Angular JS Pagination records from database using spring MVC
  6. Angular JS Multiple delete records from database using spring MVC
  7. Angular JS Update records from database using spring MVC
  8. Angular JS Delete records from database using spring MVC
  9. Angular JS Listing records from database using spring MVC
  10. Angular JS Filter and no of records/page control

Snapshot :




member-add-form-without-validation

validation-angular-js

members

Download from here essential




Please Comment if it is really helpful to you.

Sample Angular JS Demo Application using Directive (Part II)

In this application only directive is added in reference to the demo application I and delete part is also added.
Download :




angularcruddemoDirective




Enjoy ….

AngularJS CRUD sample application

Angular JS sample application.

Used :

  • Routing
  • Service
  • CRUD Operations
  • Controller
  • Bootstrap

For more details please leave the comment.




Download Link : angularcruddemo

Delete section is not done  , to get the delete part please subscribe and comment. You will get the link of the full demo in the email.