Phonegap Build: download image in one of the folders of your app

寵の児 提交于 2019-12-01 01:09:36

As far as I learned you cannot write to your own app (change items inside your app - /www folder on Android).

My solution was to save images to PERSISTENT storage (sdcard usually). You can get the path of your app's persistent storage with these steps:

function onDeviceReady() {
    console.log('Device Platform: ' + device.platform);  // returns 'Android' or 'iOS' for instance
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); 
    cacheFolderSubPath = "Android/data/com.id.myApp/cache/"; // this is app's cache folder that is removed when you delete your app! (I don't know what this path should be for iOS devices)  
}

Then inside gotFS success callback

function gotFS(fileSystem) { 
    var nturl = fileSystem.root.toNativeURL(); // cdvfile://localhost/persistent/
    window.resolveLocalFileSystemURL(nturl+cacheFolderSubPath, onResolveSuccess, onResolveFail);
}

and in onResolveSuccess

function onResolveSuccess(fileEntry){
    appCachePath = fileEntry.toNativeURL()+"/"; // file:///storage/sdcard0/Android/data/com.id.myApp/cache/ in my case but some other Androids have storage/emulated/0 or something like that ... 
    continueCustomExecution();
}

and now in continueCustomExecution() you can run your program and do whatever it is you do ... and in this case download images into appCachePath that we got earlier. You can now successfully reference images in src tags with our appCachePath+yourImageName.

Unfortunately I still don't know how to download an image successfully on iOS. I get an error code 1 with FileTransfer plugin ... (saving to file:///var/mobile/Applications/my.app.id/Documents/). Probably should save somewhere else but this is the path I get when requesting PERSISTENT FileSystem.

Cheers

I would use the folder alias as defined in the plugin docs here (https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md). Specifically cordova.file.dataDirectory. Note that this is not, afaik, under the www of your original project, but it seems to be the preferred place to store downloads. Once saved there you can resolve that to a URL that you could use to load via AJAX, or in an img tag if you are downloading graphics.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!