Showing posts with label restfull. Show all posts
Showing posts with label restfull. Show all posts

Tuesday, 29 March 2016

File upload with  data  using angular js and jersey webservice

1. jersey service.

        @POST
@Path("/public")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void get(
                               @FormDataParam("file") byte[] fileInputStream,
            @FormDataParam("file") FormDataContentDisposition fileInputDetails,
            @FormDataParam("id")String userid){

System.out.println("THis is the ID "+userid);
System.out.println("File Details : "+ fileInputDetails.getFileName());

System.out.println("Reading the String data "+ fileInputStream.toString());

String s = new String(fileInputStream);
   System.out.println("Text Decryted : " + s);

}

2.  create the angular js service,directive,controller

Service.

service('myFileService',["$http",function($http){
console.log("service is called");

this.post = function(uploadUrl, data){

var fd = new FormData();   // bunch of  key,value

console.log("uploaded URL "+uploadUrl);
console.log("uploaded data "+data);

for(var key in data) {

console.log("key is : "+ key + " , value :  "+ data[key]);
fd.append(key, data[key]);
}

$http.post(uploadUrl, fd, {
transformRequest: angular.indentity,
headers: { 'Content-Type': undefined }
})
.success(function(){
console.log("from service success");
})
.error(function(){
console.log("from service failure");
})

}


}]);

Directive : to bind the file data

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(changeEvent){
scope.$apply(function(){
                         modelSetter(scope, changeEvent.target.files[0]);
                });

});
}

};
}]);

Controller :

controller("postCTRL",['$scope','myFileService',function($scope,myFileService){
$scope.sample = {};
$scope.Submit = function(){
console.log($scope.sample.name);
var uploadedURL = "/public";
var data = $scope.sample;
myFileService.post(uploadedURL,data);
 
}
 }]);

3. HTML FORM

<form>


<p> Name : <input type="text" name="name" ng-model="sample.id" required /></p>
   
<input type="file" id="exampleInputFile" file-model="sample.file">  
   
<button ng-click="Submit()">Submit</button>

</form>
{{sample}}

</div>



Ref :
1. stackoverflow