Advertisement
Guest User

PhoneGap synchronous file download

a guest
Mar 1st, 2012
1,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* download all the images */
  2. function downloadImages(data){
  3.    var imageList = data.IMAGELIST;
  4.    var imagePath = data.IMAGEPATH;
  5.    var imageName = "";
  6.    imageData.imagePath = imagePath;
  7.    imageData.imageList = [];
  8.    var colMap = new Object();
  9.    //create column map
  10.    for (var i = 0; i < imageList.COLUMNS.length; i++) {
  11.       colMap[imageList.COLUMNS[i]] = i;
  12.    }
  13.    for (var i = 0; i < imageList.DATA.length; i++) {
  14.       imageName = imageList.DATA[i][colMap["NAME"]];
  15.       imageData.imageList.push(imageName);
  16.    }
  17.    consoleLog('Total images to download: ' + imageData.imageList.length);
  18.    downloadImage();
  19. }
  20.  
  21. /* download image syncronously */
  22. function downloadImage(){
  23.    if(imageData.imageList.length > 0){
  24.       var imageName = imageData.imageList[0];
  25.       var imagePath = imageData.imagePath;
  26.       consoleLog('Start file download: ' + imagePath + imageName);
  27.       //check if file exists, pass the function as new closure, so the variable is preserved
  28.       imageDir.getFile(imageName, {create: false}, successImageExists, (function(name, path){
  29.          return function(){
  30.             failImageExists(name, path)
  31.          }
  32.       })(imageName, imagePath));
  33.    }
  34. }
  35.  
  36. /* image exists */
  37. function successImageExists(file){
  38.    consoleLog('Image Exists: ' + file.name);
  39.    updateImageDownloadProgress();
  40. }
  41.  
  42. /* image doesn't exists */
  43. function failImageExists(imageName,imagePath){
  44.    consoleLog('image does not Exists');  
  45.    //start download  
  46.    consoleLog('Download Image To: ' + imageDir.fullPath + '/' + imageName);
  47.    ft.download(imagePath + escape(imageName), imageDir.fullPath + '/' + imageName, onImageDownload, onImageDownloadFail);
  48. }
  49.  
  50. /* on image download fail */
  51. function onImageDownloadFail(error){
  52. consoleLog('image not downloaded. Error: ' + JSON.stringify(error));
  53.    updateImageDownloadProgress();
  54. }
  55.  
  56. /* on image download success */
  57. function onImageDownload(image){
  58. updateImageDownloadProgress();
  59. }
  60.  
  61. /* update image download progress */
  62. function updateImageDownloadProgress(){
  63.    imageData.imageList = imageData.imageList.slice(1);
  64.    consoleLog('images left to download: ' + imageData.imageList.length);
  65.    if(imageData.imageList.length == 0){
  66.       imagesDownloaded = true;
  67.    } else {
  68.       downloadImage();
  69.    }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement