javascript - Upload angularjs file with progress percentage -
in webapp i've got service upload files using angularjs , multipart upload. example: https://jsfiddle.net/zg9re/3909/ works can't understand how see percentage of file during upload. don't want use xmlhttprequest
need mantain code if possible. code anyway:
var myapp = angular.module('myapp', []); myapp.directive('filemodel', ['$parse', function ($parse) { return { restrict: 'a', link: function(scope, element, attrs) { var model = $parse(attrs.filemodel); var modelsetter = model.assign; 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(){ }); } }]); myapp.controller('myctrl', ['$scope', 'fileupload', function($scope, fileupload){ $scope.uploadfile = function(){ var file = $scope.myfile; console.log('file ' ); console.dir(file); var uploadurl = "/fileupload"; fileupload.uploadfiletourl(file, uploadurl); }; }]);
html:
<div ng-controller = "myctrl"> <input type="file" file-model="myfile"/> <button ng-click="uploadfile()">upload me</button> </div>
thanks help
all code doing making $http post upload file. since standard http transaction, won't response server until timeout or success (2xx) or failure.
thus current code cannot this.
however, there module called ng-file-upload
https://github.com/danialfarid/ng-file-upload
which allows determine progress.
using in conjunction progress bar
see - http://angular-ui.github.io/bootstrap/#/progressbar
you can give feedback user :)
i have had these 2 working in professional spa.
hope helps.
the approach 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); }); };
the 3 method functions success, failure, event (progress)
i doubt $http method supports 3rd event function give go.
Comments
Post a Comment