Phonegap - How to access file in www-folder?

前端 未结 5 875
终归单人心
终归单人心 2021-01-06 12:11

I saw multiple solutions how to access a file in the www folder but no solution works for me. I test the application under iOS with the iOS-simulator.
I want to access

5条回答
  •  余生分开走
    2021-01-06 12:26

    As I just ran into the same problem but did not want to use jQuery, I thought I post my solution here as well.

    But before that an import remark: The files in the www folder of Cordova / Phone Gap are stored in the Android world as so called assets which means:

    • They are part of the .apk distribution file which is a zipped archive. Android reads the files directly from this .apk file and does not store these files separately in the local file system.
    • Therefore the files are read only and cannot be accessed with the Cordova File plugin.

    If you take a deep dive in the corresponding Android sources of Cordova you can see, that Cordova filters all URIs with a 'file' scheme, whose path starts with '/android_asset/' and handles them specially using Android's asset access functions. (Would be interesting to hear from the iOS experts how Cordova handles it in their world.)

    This means all in all that using a XMLHttpRequest is probably the only portable way to access www folder files if you need access to the file contents. (If you only need the path to the file for some system functions other methods may work as well.)

    Here is the code, filename is the path within the www folder without a "www/" prefix:

    var readFileInWWWFolder = function(filename, onSuccess, onFailure){
    
        var request = new XMLHttpRequest();
    
        request.onload = function() {
    
            var arrayBuffer = request.response;
    
            if (arrayBuffer) {
    
                onSuccess(new Uint8Array(arrayBuffer));
            }
            else {
    
                onFailure();
            }
        };
    
        request.open("GET", filename, true);
        request.responseType = "arraybuffer";
        request.send();
    };
    

    This has been tested with Cordova 4.3.0 and Android 4.4.2 (Kitkat).

提交回复
热议问题