Ionic 5 capacitor unable to fileOpener - ionic4

I am using ionic 5 capacitor to open pdf file, which I receive as blob.
downloadFile(data: Blob, fileName: string) {
this.blob = new Blob([data], { type: 'application/pdf' });
const reader = new FileReader;
reader.onload = () => {
console.log('3');
var base64data = reader.result as string;
// Save the PDF to the device
try {
Filesystem.writeFile({
path: fileName,
data: base64data,
directory: FilesystemDirectory.Data,
// encoding: FilesystemEncoding.UTF8
}).then(() => {
console.log('File Written');
Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: fileName
}).then((getUriResult) => {
console.log('getUriResult', getUriResult.uri);
const path = getUriResult.uri;
this.platform.ready().then(() => {
this.fileOpener.open(path, 'application/pdf')
.then(() => console.log('File is opened'))
.catch(error => console.log('Error openening file', error));
})
}, (error) => {
console.log('getUri', error);
});
});
} catch (error) {
console.error('Unable to write file', error);
}
}
reader.readAsDataURL(this.blob);
}
I am getting below mention error, when I run on real device
Msg: Native: tried calling FileOpener.open, but the FileOpener plugin is not installed.
Msg: Install the FileOpener plugin: 'ionic cordova plugin add cordova-plugin-file-opener2'
Msg: Error openening file plugin_not_installed
I have searched online same implementation, but for some reason it isn't working.

You need to install the cordova plugins packages and the native packages:
npm install cordova-plugin-file-opener2
npm install #ionic-native/file-opener
npm install cordova-plugin-file
npm install #ionic-native/file
ionic cap sync

Related

How to implement the Music Metadata Or Music MetaData Browser npm plugin in Cypress V10?

I tried to implement the Node plugin in Cypress Version 10, But I couldn't done it.
https://www.npmjs.com/package/music-metadata-browser#fetchurl-function
Installation is done:
npm install --save-dev music-metadata-browser
npm install --save-dev util
Added the below lines in plugin/index.js
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
};
Added the below code in e2e/validateFile.cy.js
describe('Parsing File', () => {
it('Validating Audio File', () => {
const audioURL = 'cypress/fixtures/media/Patrikios.mp3';
console.log('url: ' + audioURL);
cy.task('validateAudioFormat', audioURL).then(data => {
const allData = Object.values(data);
console.log('All data: ' + allData);
});
/******
cy.on('validateAudioFormat', (url) => {
async () => {
const metadata = await mm.fetchFromUrl(url);
console.log('url: ' + url);
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
};
});
*****/
});
});
Error:
CypressError: `cy.task('validateAudioFormat')` failed with the following error:
The task 'validateAudioFormat' was not handled in the setupNodeEvents method. The following tasks are registered: resetCoverage, combineCoverage, coverageReport
Fix this in your setupNodeEvents method here: /opt/lampp/htdocs/project/cypress.config.js
Commented block error:
taskreadAudioFiles, cypress/fixtures/media/audios/valid/Beyond_Patrick_Patrikios.mp3
CypressError
cy.task('readAudioFiles') timed out after waiting 60000ms
Anyone can help on this scenario?
Thanks!
Your project is a mixture of Cypress v9 config and Cypress v10 tests.
I presume you are on 10+ so the plugins now go in cypress.config.js
const { defineConfig } = require('cypress')
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
},
}
})

RN-fetch-blob not downloading file always failed

Im working on react native fetch blob to download the file. The file basically are in my nodejs server.
I have tried to get it from post man and its successfully working. But when i attached the api into rn-fetch-blob it shows me download failed even file exists. I have checked 10 time my installation is correct there is no issue there. Can any body help me to get out of this.
SO this is my node api router.post('/download-proof', documents.proofDownload);
proofDownload: (req, res)=> {
let filepath = path.join(__dirname,'../../../documents/')+req.body.filename
res.setHeader('Content-Disposition', 'attachment; filename=' + req.body.filename);
res.setHeader('Content-Transfer-Encoding', 'binary');
res.setHeader('Content-Type', req.body.mimetype);
res.download(filepath)
},
its working fine in postman
This one is rn-fetch-blob
let options = {
fileCache: true,
appendExt: getExt,
addAndroidDownloads: {
useDownloadManager: true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
notification: true,
description: 'Downloading file.',
path:
pathToDir +
`/${file.filename}` ,
},
path:
pathToDir +
`/${file.filename}` ,
notification: true,
};
console.log(file," docs")
console.log(options.path, pathToDir,"options")
let body = {
filename: file.filename,
mimetype: file.mimetype
}
console.log(body, "line no 62")
let url = `http://3.21.33.146:3000/download-proof`;
console.log(url);
config(options)
.fetch("POST", url,{}, JSON.stringify(body))
.progress({interval: 250}, (received, total) => {})
.then((res) => {
console.log(res, "fetch blob response")
}).catch((err) => {
console.log(err)
})
} else {
Alert.alert(
"Permission Denied!",
"You need to give storage permission to download the file"
);
}
} catch (err) {
console.log(err);
}
}
It gives me status code 16 error don't know what the problem is.

IONIC : pdf is not opening and downloading in IOS

I am creating pdf in IONIC 4. Following code is working on web and android but not on IOS. In IOS it is giving alert("Error creating file: " + err);
.catch(err => {
this.runloading = 'hide';
alert("Error creating file: " + err);
throw err;
});
if (this.platform.is("cordova")) {
this.pdfObj.getBuffer(buffer => {
var blob = new Blob([buffer], { type: "application/pdf" });
this.file
.writeFile(this.file.externalRootDirectory, "pro.pdf", blob, {
replace: true
})
.then(fileEntry => {
this.fileOpener
.open(
this.file.externalRootDirectory + "pro.pdf",
"application/pdf"
)
.catch(err => alert("Please install pdf viewer"));
this.runloading = 'hide';
})
.catch(err => {
this.runloading = 'hide';
alert("Error creating file: " + err);
throw err;
});
});
} else {
pdfmake.createPdf(docDefinition).open();
// this.pdfObj.download();
this.runloading = 'hide';
}
See this message below. There is a bug that prevents uniform experience for local file downloads on iOS.
Two choices:
1. Upload pdf to server and redownload it.
2. Await for iOS13
https://github.com/eligrey/FileSaver.js/issues/375#issuecomment-460318259

Error while cloning repo with nodegit

I'm trying to clone a repo with nodegit, but I end up with cloning nothing but .git directory. None of the my other files are being downloaded. And I got this error in the console:
Assertion failed: (t->cred), function on_headers_complete, file ../vendor/libgit2/src/transports/http.c, line 380.
Abort trap: 6
The code I wrote to clone the repo is the following:
Git.Clone(this.options.remoteUrl, this.options.localDir, this.cloneOptions)
.then((repo) => {
if (repo instanceof Git.Repository) {
console.log('Cloned');
repo.checkoutRef('refs/head/master').then((reference) => {
console.log('Checkout master completed');
this.alreadyCloned = true;
this.busy = false;
cb(null, {});
});
} else {
console.error('Failed to clone the repo');
}
})
.catch((err) => {
console.error(err);
this.busy = false;
cb(err);
});
And the clone options:
this.cloneOptions = {
fetchOpts: {
callbacks: {
certificateCheck() {
return 1;
},
credentials() {
return Git.sshKeyMemoryNew(
options.username,
options.publickey,
options.privatekey,
options.passphrase,
);
},
},
},
};
Node version: v8.5.0
OS: MacOS High Sierra (edited)
Besides:
options.publickey, // /Users/safa/.ssh/id_rsa.pub
options.privatekey, // /Users/safa/.ssh/id_rsa
Thanks in advance!

How to save Blob in Ionic

I am new to ionic framework, actually I am getting byte array as response from back end service and converting it to blob. How can I save it to PDF in ionic?
var blob = new Blob([res], { type: 'application/pdf' });
Here res is the response (byte array) from the service.
Code
var blob = new Blob([res], { type: 'application/pdf' });
let fileName="Receipt.pdf";
let filePath = (this.platform.is('android')) ?
this.file.externalRootDirectory : this.file.cacheDirectory;
this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry) => {
console.log("File created!");
this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
.then(() => console.log('File is opened'))
.catch(err => console.error('Error openening file: ' + err));
})
.catch((err) => {
console.error("Error creating file: " + err);
throw err;
});
Thanks in advance.
In order to SAVE the PDF, you'll need to use some cordova plugins. Ionic has some nice wrappers around these here. Check out the File, File Transfer, and File Opener plugins.
Here's some example code you could use once you get these plugins incorporated into your project:
var blob = new Blob([res], { type: 'application/pdf' });
//Determine a native file path to save to
let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;
//Write the file
this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry: FileEntry) => {
console.log("File created!");
//Open with File Opener plugin
this.fileOpener.open(fileEntry.toURL(), data.type)
.then(() => console.log('File is opened'))
.catch(err => console.error('Error openening file: ' + err));
})
.catch((err) => {
console.error("Error creating file: " + err);
throw err; //Rethrow - will be caught by caller
});