AngularJS中的$ http上传文件进度

win*_*toy 25 angularjs

如何从上传图像的AngularJS $ http POST请求中获取"进度"事件?是否可以在客户端执行此操作,或者我是否需要服务器在接收数据时报告进度?

Saj*_*azy 18

使用纯角度:

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;
}
Run Code Online (Sandbox Code Playgroud)

和其他地方......

// 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) + '%');
});
Run Code Online (Sandbox Code Playgroud)


dan*_*ial 17

您还可以使用简单/轻量级的angular-file-upload指令来处理这些内容.它支持使用FileAPI flash shim的非HTML5浏览器的拖放,文件进度/中止和文件上传

<div ng-controller="MyCtrl">
  <input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var $file = $files[i];
      $upload.upload({
        url: 'my/upload/url',
        file: $file,
        progress: function(e){}
      }).then(function(data, status, headers, config) {
        // file is uploaded successfully
        console.log(data);
      }); 
    }
  }
}];
Run Code Online (Sandbox Code Playgroud)


Mar*_*cok 15

我不认为$ http.post()可以用于此.

至于客户端,它应该与HTML5浏览器一起使用,但您可能必须创建自己的XMLHttpRequest对象和onprogress侦听器.请参阅AngularJS:跟踪同时上传的每个文件的状态以获取创意.