-1

Following is my service code, which is saving an image -

angular.module("app").service('fileUpload', ['$http', function ($http) {
    return {
      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(response){
          return response;
        })
        .error(function(){
        });        
      }
    }

}]);

In my Controller I am having the following code -

// Code for Image handling - START
if ($scope.myFile) {
    var file = $scope.myFile;
    console.log('file is ' + JSON.stringify(file));
    var uploadUrl = "/api/fileUpload";
    console.log("__FILE UPLOAD INFO__CHECK");
    console.log(fileUpload.uploadFileToUrl(file, uploadUrl));

}
// Code for Image handling - END

I am expecting to console.log the return data after console.log("__FILE UPLOAD INFO__CHECK"); but in console its undefined

Though I am getting the success response in the console from the AJAX request -

{
    "success": true,
    "old_path": "/tmp/ddde0cf3b8a8e4fa83a92b361e814394",
    "new_path": "/MYPROJECT_PATH/uploads/ddde0cf3b8a8e4fa83a92b361e814394.png",
    "save_image_name": "ddde0cf3b8a8e4fa83a92b361e814394.png"
}

Let me know what I am doing wrong with the callback here ?

Trialcoder
  • 5,816
  • 9
  • 44
  • 66

1 Answers1

1

It's async so you should do it with a callback function.

angular.module("app").service('fileUpload', ['$http', function ($http) {
    return {
      uploadFileToUrl: function(file, uploadUrl, successCb, errorCb){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(response){
            if(successCb){
                successCb(response);
            }
        })
        .error(function(){
            if(errorCb){
                errorCb();
            }
        });        
      }
    }

}]);
kallehj
  • 302
  • 1
  • 9
  • Please add http://pastebin.com/mAf0Y00Q handling code in your answer as well ..as it will help to the future visitors.. Service code - http://pastebin.com/sLKydv1T Handling code - http://pastebin.com/mAf0Y00Q – Trialcoder Aug 26 '14 at 08:43