Search code examples
androidioscordovapdf

Cordova 6.3.1 download PDF and open with FileSystem, FileTransfer and FileOpener2


Im banging my head against my desk because I dont seem to find any answer that works.

I want to download a PDF to the local storage of an android device, and then open it in an external reader as Android is not able to display PDF in the browser. For iOS I simply use the InAppBrowser plugin which works nice btw. Im using cordova 6.3.1.

So, this is my code:

if (cordova.platformId === "android") {
            var remoteFile = url;
            var localFileName = "tmp.pdf";

            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {

                //var fileSystemRoot = cordova.file.dataDirectory; Does not work...
                var fileSystemRoot = fileSystem.root.toURL()

                console.log(cordova.file.dataDirectory);

                    var ft = new FileTransfer();
                    ft.download(remoteFile,
                    fileSystemRoot + "tmp.pdf", function(entry) {
                        cordova.plugins.fileOpener2.open(
                            entry.toURL(),
                            'application/pdf',
                            {
                                error : function(e) {
                                    console.log('Error status: ' + e.status + ' - Error message: ' + e.message + ' - URL: ' + messageObj.url);
                            },
                                success : function () {
                                    console.log('file opened successfully');
                                    console.log(fileSystemRoot);
                                    console.log(entry.toURL());
                                }
                            }
                        );
                    }, function(error) {
                        console.log("Error in downloading");
                        console.log(error);
                    });
            }, function(error) {
                console.log("Error in requesting filesystem");
                console.log(error);
            });
}

I have tried tons of different things. fileSystem.root.fullpath, fileSystem.root.toURL(), fileSystem.root.nativeURL but I always end up with a path that does not seem to correspond with the device. I always get the success message that the download worked, adobe reader pops up but says the file is not readable. Not a surprise to me as the path it gives me is something like:

file:///data/data/ch.novalogix.novalib/files/files

That can simply not be true? I searched the whole system for the uploaded file but I dont think its downloaded. I guess I always get a wrong path...

Any ideas? Thanks in advance!


Solution

  • I used fixed paths instead of the localFileSystem.