Percentage of file upload with ng-file-upload AngularJS

0

I'm using ng-file-upload to load a file, I can currently see the percentage in console with a console.log() , but the console is in the service and I do not know how to pass it to the controller (without doing the return) to show it in HTML. The code that I have is the following:

On the Controller:

factorService.subirArchivo($scope.campo1, $scope.campo2, file).then(
    function(response){
       ...
    });

In the Service:

this.subirArchivo = function (campo1, campo2, , file) {   
        var promise = Upload.upload({
            url: "subirArchivo.php",
            method: 'post',
            file: file,
            data: {
                liderComunitario: lider,
                barrio: barrio,
                fechaReporte: fechaReporte
            }
        }).then(function (resp) {
            return resp;
        }, 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);
        });
        return promise;
    };

In the final part of the service is the console.log that shows the percentage per console and works correctly, the problem is to show it in HTML, any ideas?

    
asked by Stiven Triana 03.08.2017 в 15:54
source

1 answer

1

The problem is that you must use 'promise' to return the value:

this.subirArchivo = function (campo1, campo2, , file) {   
    //Inicializamos el constructor
    var defer = $q.defer();

    var promise = Upload.upload({
        url: "subirArchivo.php",
        method: 'post',
        file: file,
        data: {
            liderComunitario: lider,
            barrio: barrio,
            fechaReporte: fechaReporte
        }
    }).then(function (resp) {
        //return resp; En lugar de retornarlo se encapsula
        defer.resolve(resp);
    }, function (resp) {

        console.log('Error status: ' + resp.status);
        // Encapsulamos el error
        defer.reject(errorMsg);

    }, function (evt) {
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + 
        evt.config.data.file.name);
        //encapsulamos el progreso
        defer.notify(progressPercentage);
    });

     return defer.promise;
};

In the controller we process the promise

factorService.subirArchivo($scope.campo1, $scope.campo2, file)
    .then(
           function(response){
              //Respuesta satisfactoria
           }, function(error){
              // Se captura el posble error
           }, function(notify){
              //Procesamos la notificacion.
           });

I have attached the official documentation of the constructor $ q, deferred and promise.

link $ q

    
answered by 03.08.2017 / 17:21
source