Search code examples
angularjshttpfile-uploadangularjs-injectorangular-providers

Provider 'FileUpload' must return a value from $get factory method


In a web application made with AngularJs there is a page where the user can upload a file. But I have some problem. This is the Factory that makes the upload:

angular.module('app').factory('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(){
      });
  }
}]);

If I try to upload a file, console gives me this error:

"Error: [$injector:undef] Provider 'FileUpload' must return a value from $get factory method.

This is the function in the Controller:

$scope.uploadFile = function(){
    var userId = $stateParams.userId;
    var fileType = $stateParams.fileType;
    var file = $scope.myFile;
    console.log('file is ');
    console.dir(file);
    var uploadUrl = 'my_url';
    FileUpload.uploadFileToUrl(file, uploadUrl);
};

Solution

  • The pattern you're using should use service not factory. With factory you want to return the new'd up instance, with service you just provide the function.

    angular.module('app').service('FileUpload',...