Hemanth kumar H J
Hemanth kumar H J

Reputation: 67

fileUpload using angularjs

i am doing file uploading using angularjs. I am getting response but can't store that file into local disk.

controller

(function ()
{
'use strict';

angular
    .module('app.message')
    .controller('MessageController', MessageController);

/** @ngInject */
MessageController.$inject = ['$scope', '$http', '$location', 'fileUpload'];
function MessageController($scope, $http, $location, $rootScope, fileUpload)
{
    var vm = this;



    vm.uploadFile = function(){

        var file = $scope.myFile;

        console.log('file is ' );
        console.dir(file);

        var uploadUrl = "./uploads";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };
}
})();

service

(function ()
{
'use strict';

angular
    .module('app.core')
    .factory('fileUpload', fileUpload);

/** @ngInject */
function fileUpload()
{
    console.log('dsfsdfdsf');

      this.uploadFileToUrl = function(file, uploadUrl){
          console.log('inside');
           var fd = new FormData();
           fd.append('file', file);

           $http.post(uploadUrl, fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
           })

           .success(function(){
           })

           .error(function(){
           });
    }
    return this;
}
}());

view

<div flex style="max-width:700px;">
    <input type = "file" file-model = "myFile"/>
    <button ng-click = "vm.uploadFile()">upload me</button>
</div>

In console i am getting file details but i is not store in the disk. The error is always shows like fileUpload is undefined in controller.

Console error pic

Upvotes: 0

Views: 576

Answers (2)

Amulya Kashyap
Amulya Kashyap

Reputation: 2373

You should try this:

(function ()
{
'use strict';

angular
    .module('app.message')
    .controller('MessageController', MessageController);

/** @ngInject */
MessageController.$inject = ['$scope', '$http', '$location', '$rootScope'];
function MessageController($scope, $http, $location, $rootScope, fileUpload)
{
    var vm = this;



    vm.uploadFile = function(){

        var file = $scope.myFile;

        console.log('file is ' );
        console.dir(file);

        var uploadUrl = "./uploads";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };
}
})();

Upvotes: 1

shaouari
shaouari

Reputation: 236

you forget $rootScope injection

/** @ngInject */
MessageController.$inject = ['$scope', '$http', '$location','$rootScope', 'fileUpload'];
function MessageController($scope, $http, $location, $rootScope, fileUpload)
{
    var vm = this;



    vm.uploadFile = function(){

        var file = $scope.myFile;

        console.log('file is ' );
        console.dir(file);

        var uploadUrl = "./uploads";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };
}
})();

Upvotes: 0

Related Questions