How image to image upload in service using angularjs

 We learn image upload in service or save database using angularjs.In this tutorial we explain how to upload a pic and after upload pic how to save and preview on screen using angularjs.

 In this example we use custom directive for upload image. it simple to use for image uploading

Let's Start how to upload image the angular js.

Example:-

Html:-

<!DOCTYPE html>
<html ng-app="myapp">

  <head>
    <meta charset="utf-8" />
    <title>Image Upload</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="myCtrl">
    <input type="file" file-model="myFile"/>
    <button ng-click="uploadFile()">upload me</button>
  </body>

</html>



Script:-

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

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
    
    $scope.uploadFile = function(){
        var file = $scope.myFile;       
        var uploadUrl = "/savefile";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };
    
}]);


Now we have set all things above script add in head section or before body end of page
It work fine let see the output.




Hope you like the post .Please share and comment below or customer care section.

Thanks. 



Post a Comment

0 Comments