Read file error after downloaded (sometimes)


#1

Hi I am trying to download a file in a chat App, and immediately i am tryin to opening…

I have this code…

openFile(file, time, extfilePath){
let nameFile = ‘ang-’ + time + ‘-’+ file;
let fileExtension = nameFile.slice((nameFile.lastIndexOf(".") - 1 >>> 0) + 2);
let filePath = this.file.documentsDirectory;
this.file.resolveLocalFilesystemUrl(filePath + nameFile).then(() => {
this.openFileFromDisk(filePath+nameFile, this.choseMimeType(fileExtension));
console.log(“archivo abierto”);
}, (error) => {
console.log(JSON.stringify(error));
this.downloadFile(nameFile, filePath, extfilePath, this.choseMimeType(fileExtension));
console.log(“archivo descargadado y abierto”);
});
}

openFileFromDisk(path, mimeType){
console.log(path);
this.fileOpener.open(path, mimeType).then(() => {
console.log(‘File is opened’);
}).catch(e => {
console.log(‘Error opening file’, e);
let toast = this.toastCtrl.create({
message: ‘Hubo un error al abrir el archivo por favor intentelo nuevamente.’,
duration: 5000,
position: ‘top’
});
toast.onDidDismiss(() => {
//console.log(‘Dismissed toast’);
});
toast.present();
//console.log('download completed: ’ + entry.toURL());
});
}

downloadFile(fileName, localfilePath, extfilePath, fileExtension) {
let completeUrl:any;
let url = encodeURI(extfilePath);
this.fileTransfer = this.transfer.create();
this.fileTransfer.onProgress((progressEvent) => {
this.percent = progressEvent.loaded / progressEvent.total * 100;
this.percent = Math.round(this.percent);
console.log('Downloaded: ’ + this.percent);
});
this.fileTransfer.download(url, localfilePath + fileName, true).then((entry) => {
let toast = this.toastCtrl.create({
message: ‘El archivo ’ + fileName + ’ se descargo correctamente en la carpeta Download de su telefono.’,
duration: 5000,
position: ‘top’
});
toast.onDidDismiss(() => {
//console.log(‘Dismissed toast’);
});
toast.present();
//console.log('download completed: ’ + entry.toURL());
this.completeUrl = entry.toURL();
}).then((entry)=>{
setTimeout(() => {
this.openFileFromDisk(this.completeUrl, this.choseMimeType(fileExtension));
},400);
//console.log(completeUrl);
}, (error) => {
let toast = this.toastCtrl.create({
message: ‘Error en la descarga, intentelo nuevamente’,
duration: 5000,
position: ‘bottom’
});
toast.onDidDismiss(() => {
//console.log(‘Dismissed toast’);
});
toast.present();
//console.log('download failed: ’ + error);
});
}

I call the openFile() method from this html code
<img style=“width:20%; display:inline;” src=“assets/imgs/file-1.png” id=“ang-{{message.time}}{{message.fileName}}” [alt]=“message.fileName” (click)=“openFile(message.fileName, message.time, message.fileURL)”>

as you see first the code check the file is downloaded and is true it open the file, but is not call the download file and open again…

my problem is when the file is download the file is not openned and I need to call again the openfile() method and it open the file…

what is wrong on my code?