使用angularjs上传文件

ttcibm8c  于 11个月前  发布在  Angular
关注(0)|答案(2)|浏览(103)

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

控制器

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

视图

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


在控制台中,我正在获取文件详细信息,但我没有存储在磁盘中。错误总是显示fileUpload在控制器中未定义。


的数据

mdfafbf1

mdfafbf11#

你应该试试这个:

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

字符串

bxgwgixi

bxgwgixi2#

您忘记了$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);
    };
}
})();

字符串

相关问题