programing

AngularJS에서 $http 업로드 파일 진행률

iphone6s 2023. 10. 4. 21:02
반응형

AngularJS에서 $http 업로드 파일 진행률

Angular에서 '진행' 이벤트를 받으려면 어떻게 해야 합니까?이미지를 업로드하는 JS $http POST 요청?클라이언트 측에서 가능한가요, 아니면 서버가 데이터를 받을 때 진행 상황을 보고해야 하나요?

순각 사용:

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;
}

그리고 다른 곳에서...

// 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) + '%');
});

또한 이러한 작업을 처리하는 단순/경량 각도 파일 업로드 지시문을 사용할 수 있습니다.FileAPI flash shim으로 HTML5 브라우저가 아닌 사용자를 위한 드래그 앤 드롭, 파일 진행/중단 및 파일 업로드를 지원합니다.

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

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);
      }); 
    }
  }
}];

저는 http.post () 달러는 이것에 사용될 수 없다고 생각합니다.

클라이언트 측의 경우 HTML5 브라우저와 함께 작동해야 하지만 아마도 자신만의 XMLHtpRequest 개체를 만들어야 할 것입니다.onprogress듣는 사람각도 참조JS: 아이디어를 얻기 위해 각 파일이 동시에 업로드되는 상태를 추적합니다.

Angular에서 처리할 수 있는 것이 내장되어 있지 않다고 생각합니다.

저는 당신이 jQuery File Upload와 같은 것을 사용하는 것이 최선이라고 생각합니다.솔루션에 대한 아이디어는 반환되는 서비스를 만드는 것입니다.{progress:0}를 기본값으로 설정한 다음 자체 내부에 jQuery File Upload의 진행률 업데이트 콜백을 구현합니다. 이 콜백은 단순히 진행률을 계속 업데이트합니다.Angular의 바인딩 덕분에 업로드 진행 상황이 동기화 될 것입니다.

angular.module('myApp.services', [])
  .factory('Uploader', function() {
  var uploaderService = {};

  var status = { progress: 0 };

  uploaderService.upload = function(inputEl) {
    inputEl.fileupload({
      /* ... */
      progressall: function (e, data) {
        status.progress = parseInt(data.loaded / data.total * 100, 10);
      }
    });
  };

  return uploaderService;
});

다음은 또 다른 해결책입니다.

window.XMLHttpRequest = (function (orig) {
    if (orig) {
        var intercept = [],
            result = function () {
            var r = new orig();

            if (r.upload) {
                $(r).on(
                    'abort error load loadend loadstart progress',
                    function (e) {
                        $(document).trigger('upload.XHR', e);
                    }
                );
            }

            if (intercept.length) {
                intercept[0].push({
                    request:r
                });
            }

            return r;
        };

        result.grab = function (f) {
            intercept.unshift([]);
            f();
            return intercept.shift();
        };

        return result;
    }

    return function () {
        try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
        throw new Error("This browser does not support XMLHttpRequest.");
    };
}(window.XMLHttpRequest));

주의:

  • AngularJS는 현재 다음에 대한 참조를 저장합니다.window.XMLHttpRequest비공개로XHRvariable을 다음과 같이 사용합니다.new XHR(). 이것이 바뀔지는 의문이지만, 위의 심과 같은 코드는 잘 작동할 것입니다.

  • 모질라는 몇 가지 확장 기능을 가지고 있습니다.XMLHttpRequest선택적 인수를 사용합니다.위의 코드는 이를 처리하지 않지만 Angular.JS는 어쨌든 이 확장자들을 사용하지 않습니다.

  • 사용 방법 중 하나(현재 요청을 모두 표시하고 일부 "취소" 버튼을 구현하려는 경우):

$(document).on('upload.XHR', function (_e, e) {
   switch (e.type) {
       // do your thing here
   }
});
  • 또 다른 사용 방법:
var list = window.XMLHttpRequest.grab(function () {
    // start one or more $http requests here, or put some code
    // here that indirectly (but synchronously) starts requests
    $http.get(...);
    couchDoc.save();
    couchDoc.attach(blob, 'filename.ext');
    // etc
});

list[0].request.upload.addEventListener(...);
  • 또는 위의 코드에 대한 수정 사항과 함께 두 가지 접근 방식을 결합할 수 있습니다.

당신은 이것을 사용하여 간단한 각도함수를 이용하여 파일을 업로드하고 $scope.progressBar 변수를 이용하여 업로드 진행 상황을 확인할 수 있습니다...

$scope.functionName = function(files) {
   var file = files[0];
   $scope.upload = $upload.upload({
   url: 'url',
   method: 'POST', 
   withCredentials: true, 
   data: {type:'uploadzip'},
   file: file, // or list of files ($files) for html5 only 
 }).progress(function(evt) {
   console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
   $scope.progressBar = parseInt(100.0 * evt.loaded / evt.total);
 }).success(function(data, status, headers, config) {
   console.log('upload succesfully...')
 }).error(function(err) {
   console.log(err.stack);
 }) 
}

언급URL : https://stackoverflow.com/questions/14289637/http-upload-file-progress-in-angularjs

반응형