Not able to load image from android internal memor

2019-07-18 16:02发布

问题:

Develop web app from Android using Worklight 6.2 (Cordova 3.4)

I am not able to load image using Cordova file system api:

function onFileSystemSuccess(fileSystem) {

    var filePath = "UserSignature/SignatureImage.png";
    fileSystem.root.getFile(filePath, {create: true}, function gotFileEntry(fileEntry){
        fileEntry.file(function gotFile(file){
            var reader = new FileReader();
            reader.onloadend = function(evt) {
               alert("Read as data URL");
               document.getElementById("config_SignatureImg").src = evt.target.result;
            };
            reader.readAsDataURL(file);

        }, function fail(evt){

        });
    }, function fail(message){
        alert("failed");
    });

}

However, it works when I save it in the sdcard. I am not storing it in the SDCard for security constraints.

I am doing the saving of image through native code as follows:

String folderName = "UserSignature";
File parentDirectory = new File(this.getContext().getFilesDir(), folderName);

if(!parentDirectory.exists()){
    parentDirectory.mkdirs();
}

// Save the signature as image to file  
Bitmap bm = Bitmap.createBitmap(this.getDrawingCache());
saveSignatureAsImage(bm, parentDirectory, getSignatureFileName());

private void saveSignatureAsImage(Bitmap bm, File dir, String name) {
    File signature = new File(dir, name + ".png");

    // Save the signature file to sd card
    try {
        FileOutputStream out = new FileOutputStream(signature);
        bm.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    setSignatureFilePath(dir.getPath());
    Log.e("AMBW", "Succesfully saved signature in dir" + dir.getPath());
    Log.e("AMBW", "Succesfully saved signature in file" + signature.getPath());
}

I would really appreciate if someone could help me out with this issue.

回答1:

I am not sure where you are actually trying to read the file. If the file you are reading is in the asset folder like /www then you cant access it using the Cordova file API. Check this link for more information. https://stackoverflow.com/a/8966227/3456790

However, you could use a cordova plugin to read a file using native code. You could do something like this.

AssetManager assetManager = cordova.getActivity().getAssets();
inputStream = assetManager.open("www/default/data/" + fileName + ".json" );
        if(inputStream != null) {
            buffer = new byte[inputStream.available()];
            inputStream.read(buffer);

            logger.info("Found file " + fileName);

            jsonResult  = new JSONArray(new String(buffer, "UTF-8"));
        }

Hope that gives you some ideas.