Search code examples
cordovaionic-frameworkcordova-pluginsngcordova

Given the full path to a file, how you use the new Cordova file plugin?


The Cordova file plugin is well documented here: http://ngcordova.com/docs/plugins/file/

The issue I'm having however, is that the methods often require a FileSystem object, and a string representing the file name. However what I have is the full path of the file which can be from any readable FileSystem. As a matter of fact, the file path is retrieved using the Cordova camera plugin( http://ngcordova.com/docs/plugins/camera/) using the destinationType Camera.DestinationType.FILE_URI.

With that said, how do I call the readAsBinaryString(FileSystem, fileName) method with just the fully resolved file path?


Solution

  • You might be looking for window.resolveLocalFileSystemURL. The File plugin uses a bit of the html5 calls to do its work.

    Here's an example from a document import method I've got. (It's very simplified; the full file is up here if you're morbidly curious: https://github.com/adapt-it/adapt-it-mobile/blob/master/www/js/views/DocumentViews.js)

    importFile = function (file, project) {
        var reader = new FileReader();
        reader.onloadend = function (e) {
            // do your parsing here
        };
        reader.readAsText(file);
    }
    
    window.resolveLocalFileSystemURL(fileURL,
        function (entry) {
            entry.file(
                function (file) {
                    importFile(file);
                },
                function (error) {
                    console.log("FileEntry.file error: " + error.code);
                }
            );
        },
        function (error) {
            console.log("resolveLocalFileSystemURL error: " + error.code);
        });
    

    Raymon Camden also has a great blog series explaining the details of the file API as it relates to Cordova. Here's the one on reading a file: http://www.raymondcamden.com/2014/07/15/Cordova-Sample-Reading-a-text-file.