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

前端 未结 2 924
夕颜
夕颜 2021-01-07 08:21

I am able to download an image if I specify the path directly with

file:///storage/sdcard0/

How can I save an image to my one o

相关标签:
2条回答
  • 2021-01-07 09:18

    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.

    0 讨论(0)
  • 2021-01-07 09:18

    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

    0 讨论(0)
提交回复
热议问题