2017-07-31 41 views
2

,以顯示文件上傳進度條我使用這個指令如何使用angularjs

myApp.directive('fileModel', ['$parse', function ($parse) { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      var model = $parse(attrs.fileModel); 
      var modelSetter = model.assign; 
      console.log(modelSetter) 
      element.bind('change', function(){ 
       scope.$apply(function(){ 
        modelSetter(scope, element[0].files[0]); 
       }); 
      }); 
     } 
    }; 
}]); 

和我的服務是

myApp.service('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(){ 
     }); 
    } 
}]); 
在我的控制器

$scope.uploadFile = function(){ 
     var file = $scope.myFile; 
     console.log('file is '); 
     console.dir(file); 
     var uploadUrl = "/fileUpload"; 
     fileUpload.uploadFileToUrl(file, uploadUrl); 
    }; 

我的問題是如何在將圖片上傳到網址時顯示進度條我JSfiddle URl https://jsfiddle.net/JeJenny/ZG9re/

回答

1

試試這個代碼,對我工作的罰款

this.uploadFileToUrl = function (file, uploadUrl, progressCB) { 
    var fd = new FormData(); 
    fd.append('file', file); 
    $http.post(uploadUrl, fd, { 
     transformRequest: angular.identity, 
     headers: { 'Content-Type': undefined }, 
     uploadEventHandlers: { 
      progress: progressCB 
     } 
    }) 
     .success(function() { 
     }) 
     .error(function() { 
     }); 
} 

$scope.uploadFile = function() { 
    var file = $scope.myFile; 
    console.log('file is '); 
    console.dir(file); 
    var uploadUrl = "/fileUpload"; 
    fileUpload.uploadFileToUrl(file, uploadUrl, , function (e) { 
     if (e.lengthComputable) { 
      var progressBar = (e.loaded/e.total) * 100; 
      console.log(progressBar); 
      //here you will get progress, you can use this to show progress 
     } 
    }); 
}; 
+0

得到類型錯誤不是一個函數 '類型錯誤:一個是不是function' –

+0

@ User_3535在服務或控制器? – byteC0de

+0

不知道,在angualr.js文件中出現錯誤, –

0

我會說。使用此ng-file-upload指令。它具有內置的這些功能。

$scope.upload = function (file) { 
     Upload.upload({ 
      url: 'upload/url', 
      data: {file: file, 'username': $scope.username} 
     }).then(function (resp) { 
      console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data); 
     }, function (resp) { 
      console.log('Error status: ' + resp.status); 
     }, function (evt) { 
      var progressPercentage = parseInt(100.0 * evt.loaded/evt.total); 
      console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name); 
     }); 
    }; 

看到演示here