Thursday, January 29, 2015

PhoneGap plugins: file transfer - download

file-transfer plugin needed.
Install it with this: 

phonegap plugin add org.apache.cordova.file-transfer

Here is my example.html(within javascript code).
This example provides a file download(pay attention to change the value of file url to download):

<!DOCTYPE html>
<html>
  <head>
    <title>PhoneGap Transfer - download - Example Page</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // !! Assumes variable fileURL contains a valid URL to a path on the device,
//    for example, cdvfile://localhost/persistent/path/to/downloads/

    function startDownload () {
        alert ("invoked startDownload function...") ;
        var fileTransfer = new FileTransfer();
        var downloadUrl = encodeURI("http://www.yoursite.com/file_to_download.txt");

        var relativeFilePath = "./papa-francesco.sqlite";  // using an absolute path also does not work

        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
           var fileTransfer = new FileTransfer();
           fileTransfer.download(
              downloadUrl,

              // The correct path!
              fileSystem.root.toURL() + '/' + relativeFilePath,

              function (entry) {
                 console.log("Success");
              },
              function (error) {
                 console.log("Error during download. Code = " + error.code);
              }
           );
        });
  
    }
    </script>
  </head>
  <body>
    <p><button onclick="startDownload()">start download</button></p>
  </body>
</html>


Bye...

No comments:

Post a Comment