cyrielo

JavaScript PhoneGap Api For Android / File Download

Sep 10th, 2014
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. document.addEventListener('deviceready',init,false);
  2.  
  3. function init()
  4. {
  5.     window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemError);
  6.    
  7. }
  8. function fileSystemSuccess(FileSystemObj)
  9. {
  10.     AppCacheDir = "Android/data/com.mentable.android/cache";
  11.     var fileSystemName = FileSystemObj.name;
  12.     var fileSystemRoot = FileSystemObj.root;
  13.     console.log("the file system name is "+fileSystemName);
  14.     console.log('File system path is = '+fileSystemRoot.fullPath);
  15.     fileSystemRoot.getDirectory(AppCacheDir, {create: true, exclusive: false}, gotDir, lostDir);
  16. }
  17. function fileSystemError()
  18. {
  19.     console.log('access to file system failed');
  20. }
  21. function gotDir(DirEntry)
  22. {
  23.     var entryReader = DirEntry.createReader();
  24.     entryReader.readEntries(gotFilesInDir, lostFilesInDir);
  25.     console.log('Am in the directory :)');
  26.     var dir_full_path = DirEntry.fullPath;
  27.     console.log("The Absolute path of this directoty is "+dir_full_path);
  28.     var tartan_image = 'http://www.scotsconnection.com/uploads/images_products/1831.jpg';
  29.     downloadFile(tartan_image,dir_full_path+'/lovely_tartan.jpg');
  30.     var entryReader2 = DirEntry.createReader();
  31.     entryReader2.readEntries(gotFilesInDir, lostFilesInDir);
  32. }
  33. function lostDir(ErrorObj)
  34. {
  35.     console.log('lost access to dir '+ErrorObj.code);
  36. }
  37. function gotFilesInDir(DFileEntry)
  38. {
  39.     console.log("There are "+DFileEntry.length+" files in this dir");
  40.     for(var i = 0 ; i < DFileEntry.length; i++)
  41.     {
  42.         console.log('File name is '+DFileEntry[i].name);
  43.     }
  44. }
  45. function lostFilesInDir()
  46. {
  47.     console.log('Holy crap lost access to files in dir ):');
  48. }
  49. function downloadFile(url, target)
  50. {
  51.     var fileTransferHandle = new FileTransfer();
  52.     var source = encodeURI(url);
  53.     fileTransferHandle.download(source, target, fileDownloaded, downloadFailed, false);
  54. }
  55.  
  56. function fileDownloaded(downloadEntry)
  57. {
  58.     console.log("Hey File download was successfull cheers. :)");
  59. }
  60. function downloadFailed()
  61. {
  62.     console.log("Oh no file download was not successfull (>:<)");
  63. }
Add Comment
Please, Sign In to add comment