使用angularjs的fileUpload

时间:2016-03-10 10:18:01

标签: angularjs

我正在使用angularjs进行文件上传。我收到了响应,但无法将该文件存储到本地磁盘中。

控制器

/register

服务

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

视图

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

在控制台中我收到文件详细信息,但我没有存储在磁盘中。 始终显示错误,例如fileUpload在控制器中未定义。

Console error pic

2 个答案:

答案 0 :(得分:1)

亲爱的

你应该试试这个:

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

谢谢&干杯:)

答案 1 :(得分:0)

你忘了$ rootScope 注入

/** @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);
    };
}
})();