When the file is downloaded I want to show progress bar

When the file is downloaded I want to show progress bar. How can i do that

download(event,item){


  let targetPath = this.file.documentsDirectory;
  let getUrl = item._meta_gallery_images
  //
  let downloadFileName = getUrl.substr(getUrl.lastIndexOf('/') + 1); 
    this.file.createDir(targetPath,'video',true)
 .then((res) => console.log('createDir video res',res))
 .catch((err) => console.log('createDir video err',err));

const fileTransfer: FileTransferObject = this.transfer.create();
 const url =   getUrl;
var URL = encodeURI(url);
  fileTransfer.download(URL, this.file.externalDataDirectory +'video/'+ downloadFileName ,true).then((entry) => {
    console.log('download complete: ' + entry.toURL());
   
  }, (error) => {
    // handle error
    console.log('err',error);
  });
}
1 Like

add this listener after your filetransfer object creation

            fileTransfer.onProgress((progressEvent) => {
		      	console.log(progressEvent);
				var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
				this.progress = perc;
		    });

and then you could have a progress bar in your view with html and css like this
HTML:

            <div class="progress-outer">
			    <div class="progress-inner" [style.width]="progress + '%'">
			        {{progress}}%
			    </div>
			</div>

CSS:

    .progress-outer {
        width: 96%;
        margin: 10px 2%;
        padding: 3px;
        text-align: center;
        background-color: #f4f4f4;
        border: 1px solid #dcdcdc;
        color: #fff;
        border-radius: 20px;
    }
 
    .progress-inner {
        min-width: 15%;
        white-space: nowrap;
        overflow: hidden;
        padding: 5px;
        border-radius: 20px;
        background-color: #16A1A4;
    }

Sir, where put your function inside my function?

download(event,item){


  let targetPath = this.file.documentsDirectory;
  let getUrl = item._meta_gallery_images
  //
  let downloadFileName = getUrl.substr(getUrl.lastIndexOf('/') + 1); 
    this.file.createDir(targetPath,'video',true)
 .then((res) => console.log('createDir video res',res))
 .catch((err) => console.log('createDir video err',err));

 const fileTransfer: FileTransferObject = this.transfer.create();
 const url =   getUrl;
 var URL = encodeURI(url);
  fileTransfer.onProgress((progressEvent) => {
    console.log(progressEvent);
	var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
	this.progress = perc;
  });
  fileTransfer.download(URL, this.file.externalDataDirectory +'video/'+ downloadFileName ,true).then((entry) => {
    console.log('download complete: ' + entry.toURL());
   
  }, (error) => {
    // handle error
    console.log('err',error);
  });
}

its not working. download percentage showing infinity how can i fix that?

does your file get downloaded successfully? if so check the downloaded file. is it all Ok?

ya file is download properly

below my current
.ts

download(event,item){

let targetPath = this.file.documentsDirectory;
  let getUrl = item._meta_gallery_images
  let downloadFileName = getUrl.substr(getUrl.lastIndexOf('/') + 1); 
    this.file.createDir(targetPath,'video',true)
 .then((res) => console.log('createDir video res',res))
 .catch((err) => console.log('createDir video err',err));

 const fileTransfer: FileTransferObject = this.transfer.create();
 const url =   getUrl;
 var URL = encodeURI(url);
  fileTransfer.onProgress((progressEvent) => {
    console.log(progressEvent);
  var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
  this.progress = perc;
  });
  fileTransfer.download(URL, this.file.externalDataDirectory +'video/'+ downloadFileName ,true).then((entry) => {
    console.log('download complete: ' + entry.toURL());
   
  }, (error) => {
    // handle error
    console.log('err',error);
  });
}

.html

      <div class="progress-outer">
          <div class="progress-inner" [style.width]="progress + '%'">
              {{progress}}%
          </div>
      </div>

.scss

 .progress-outer {
        width: 96%;
        margin: 10px 2%;
        padding: 3px;
        text-align: center;
        background-color: #f4f4f4;
        border: 1px solid #dcdcdc;
        color: #fff;
        border-radius: 20px;
    }
 
    .progress-inner {
        min-width: 15%;
        white-space: nowrap;
        overflow: hidden;
        padding: 5px;
        border-radius: 20px;
        background-color: #16A1A4;
    }

please check. how can i fix that?

I have fixed my issue . but now i’m want to do when user click on download on that time showing the progress and after complete the download progress bar is automatically hide . how can i do that?

you can use the *ngIf directive,
initialize progress to a negative value for example:

progress = -1;

and

      <div class="progress-outer" *ngIf="progress>=0 && progress<100">
          <div class="progress-inner" [style.width]="progress + '%'">
              {{progress}}%
          </div>
      </div>

this for progress bar hide and show?

yes, according to w3schools
The ng-if directive removes the HTML element if the expression evaluates to false.

If the if statement evaluates to true, a copy of the Element is added in the DOM.

The ng-if directive is different from the ng-hide, which hides the display of the element, where the ng-if directive completely removes the element from the DOM.

ok @amin-setayeshfar let me check

downloaded successfully but progress-bar is not showing

I followed your code everything works but the progress bur only changes after file downloaded. I have logged and checked the console for this.progress value, the value changes nice but did not affect the html and style.

hello, you need to use NgZone like this.

import {NgZone} from '@angular/core';

constructor(public _zone: NgZone) {

    this.fileTransfer.onProgress((progressEvent) => {
      this._zone.run(() =>{
        var perc = (progressEvent.lengthComputable) ?  Math.floor(progressEvent.loaded / progressEvent.total * 100) : -1;
        console.log(progressEvent,'%',perc);
        this.progress = perc;
      });
    });  
2 Likes

just use a *ngIf boolean condition after filetransfer.download

Follow this exemple using observable:

HTML:

<ion-item *ngIf="aux != 0">
    <ion-text >{{aux}}% </ion-text>
    <ion-label class="porcentagem"><ion-progress-bar [value]="porcentagem"></ion-progress-bar></ion-label>
    <ion-button color="danger" (click)="cancelarEnvio()">Cancelar</ion-button>
  </ion-item>

Pagina:

 ngOnInit() {
    this.apiService.getPorcentagemObservable().subscribe(res => {
      console.log('Novo Valor: ', res)
      
      if(res == 1){
        this.porcentagem = res / 100
        this.aux = res
      } else if (res == 100) {
        this.porcentagem = 0
        this.aux = 0
        this.changeDetectorRef.detectChanges()
      } else {
        this.porcentagem = res / 100
        this.aux = res
        this.changeDetectorRef.detectChanges() 
      }
    })
  }

Serviço:

import { Camera, CameraOptions, MediaType } from '@ionic-native/camera/ngx';
import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer/ngx';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  fileTransfer: FileTransferObject = this.transfer.create();
  private porcentagem = new BehaviorSubject(0)
  usuario:any   
  codigo:any


//=============================================> Construtor <=========================================

  constructor
  ( 
    private http: HTTP,
    private transfer : FileTransfer,

  ) {}

  salvarMalote(payload){
    console.log(payload)
    
    var filePath = payload.imageURI;
    var filename = filePath.split("/").pop();
    var extencao = filename.split(".").pop();
    let server
    var options : FileUploadOptions;

    let url //My url
    server = url 
    options = {
        fileKey: "file",
        fileName: filename,
        chunkedMode: false,

        headers: {
            Connecection: "close"
        },
        params: {
            Codigo: this.codigo,
            descricao: payload.descricao,
            email: this.usuario
        }
    }

 
    //Verificação de progresso 

    this.fileTransfer.onProgress((progressEvent) => {
      let perc
      if (progressEvent.lengthComputable) {
        perc = Math.floor((progressEvent.loaded / progressEvent.total) * 100);
        this.setPorcentagem(perc)
      } else {
        perc ++
      }
    });

    //upload

    console.log(filePath, server, options)
    return this.fileTransfer.upload(filePath, server, options).then((data) =>{
      let retorno = JSON.parse(data.response)
      console.log(retorno)
      if (retorno.sucesso) {
        this.setPorcentagem(100)
      } else {
        console.log('erro')
      }
      console.log()
    }, (error) => {
      console.log(error)
    });
  }

  //Metodos Observable

  setPorcentagem(perc){
    if (perc == 100) {
      this.porcentagem.next(0)
    } else{
      this.porcentagem.next(perc)
    }
  }

  getconst(): number {
    return  this.porcentagem.getValue()
  }
  
  getPorcentagemObservable():Observable<number>{
    return this.porcentagem.asObservable()
  }

  abortar(){
    this.porcentagem.next(0)
    this.fileTransfer.abort()
  }

}