Search code examples
androidcordovacordova-plugins

read uploaded vcf file from server


I have uploaded vcf file successfully on server on getting help from my previous question (the one which is edited)

Now I need a help in how to read that vcf file or vcard from server and display as a contact number and contact name in my phonegap app.

plugin used cordova-plugin-file-transfer

Can anyone help on this ?


Solution

  • Using plugin cordova-plugin-file-transfer https://github.com/apache/cordova-plugin-file-transfer you can download file from server.

    For Read vcf file, you need https://github.com/nilclass/vcardjs JavaScript based library. you can directly use .js files.

    You can follow below example.

     window.requestFileSystem(window.TEMPORARY, 1 * 1024 * 1024, function (fs) {
    
            console.log('file system open: ' + fs.name);
            var fileName = "temp.vcf";
            var dirEntry = fs.root;
            dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
    
               download(fileEntry,"server-path-to-file.vcf");
    
            }, onErrorCreateFile);
    
        }, onErrorLoadFs);
    
    
    
    
    function download(fileEntry, uri) {
    
        var fileTransfer = new FileTransfer();
        var fileURL = fileEntry.toURL();
    
        fileTransfer.download(
            uri,
            fileURL,
            function (entry) {
                console.log("Successful download...");
                console.log("download complete: " + entry.toURL());
                readFile(entry);
            },
            function (error) {
                console.log("download error source " + error.source);
                console.log("download error target " + error.target);
                console.log("upload error code" + error.code);
            },
            null, // or, pass false
            {
                //headers: {
                //    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
                //}
            }
        );
    }
    
    
    function readFile(fileEntry) {
        fileEntry.file(function (file) {
    
            var reader = new FileReader();
    
            reader.onloadend = function () {
    
                console.log("Successful file read: " + reader.result);
                reader.parseVCard(reader.result);
    
            };
    
            reader.readAsText(file);
    
        }, onErrorReadFile);
    }
    
    function parseVCard(vCarddata){
    VCF.parse(vCarddata, function(vcard) {
      // this function is called with a VCard instance.
      // If the input contains more than one vCard, it is called multiple times.
      console.log("Formatted name", vcard.fn);
      console.log("Names", JSON.stringify(vcard.n));
    });
    //Fore more help:https://github.com/nilclass/vcardjs
    }