在文件上传过程中为进度提供角度$http $watch

angular $http $watch for progress during file uploading

本文关键字:watch http 文件 过程中      更新时间:2023-09-26

我有一个这样的函数:

$scope.fileUpload = function (files) {
                angular.forEach(files, function () {
                    var fd = new FormData();
                    fd.append('files[]', files[0]);
                    $http.post('/my-url', fd, {
                        transformRequest: angular.identity,
                        headers: {
                            'Content-Type': undefined}
                    }).then(function (data) {
                        console.log(data);
                    });
                });
            };

和模板:

<input type="file"
               name="files[]"
               id="fileUploaderButton_contentFormFiles"
               onchange="angular.element(this).scope().fileUpload(files)"
               multiple>
<div class="progress" id="fileUploaderProgressbar_contentFormFiles">
    <div class="progress-bar progress-bar-striped active"
         role="progressbar"
         aria-valuenow="{{progress}}"
         aria-valuemin="0"
         aria-valuemax="100"
         style="min-width: 2em; width: {{progress}}%">
        <span>{{progress}}%</span>
    </div>
</div>

如何$watch上传文件的传输值(字节),以便我可以在请求期间更新进度条中的 {{progress}}$http(使用本机角度功能)?提前谢谢。

不是你想要的答案,但你的方法错了

您应该使用 ng-file-upload,这是标准的角度方法,并支持上传进度跟踪

非常感谢

大家的建议。我的解决方案是使用 XMLHttpRequest 而不是$http服务:

$scope.fileUpload = function (files) {
                angular.forEach(files, function () {
                    var fd = new FormData();
                    fd.append('files[]', files[0]);
                    var xhr = new XMLHttpRequest();
                    xhr.upload.onprogress = function (event) {
                        $scope.progress = Math.floor((event.loaded / event.total) * 100);
                        console.log(event.loaded + ' / ' + event.total);
                    }
                    xhr.open("POST", '/my-url', true);
                    xhr.send(fd);
                });
            };

您可以使用 ng-file-upload 指令。它支持非HTML5浏览器的拖放,文件进度/中止和文件上传。

.HTML:

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

.JS:

//make sure you inject angularfileupload
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);
      }); 
    }
  }
}];