Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$http upload file progress in AngularJS

Tags:

How can I get a 'progress' event from my AngularJS $http POST request that is uploading an image? Is it possible to do this client-side, or do I need the server to report the progress as it receives the data?

like image 630
winduptoy Avatar asked Jan 12 '13 02:01

winduptoy


1 Answers

Using pure angular:

function upload(data) {     var formData = new FormData();     Object.keys(data).forEach(function(key){formData.append(key, data[key]);});     var defer = $q.defer();     $http({         method: 'POST',         data: formData,         url: <url>,         headers: {'Content-Type': undefined},         uploadEventHandlers: { progress: function(e) {             defer.notify(e.loaded * 100 / e.total);         }}     }).then(defer.resolve.bind(defer), defer.reject.bind(defer));     return defer.promise; } 

and somewhere else ...

// file is a JS File object upload({avatar:file}).then(function(responce){     console.log('success :) ', response); }, function(){     console.log('failed :('); }, function(progress){     console.log('uploading: ' + Math.floor(progress) + '%'); }); 
like image 57
Sajjad Shirazy Avatar answered Oct 11 '22 11:10

Sajjad Shirazy