Skip to content Skip to sidebar Skip to footer

Saving Dataurl(base64) To File On Phonegap (android)

I'm converting canvas to dataURL(base64) type and I wanted to save it to phone filesystem using PhoneGap's writer but without success (I get broken file which I cannot open) - here

Solution 1:

FileWriter’s write method does not take a base64 string. According to the docs (http://docs.phonegap.com/en/edge/cordova_file_file.md.html#FileWriter) text will be encoded as UTF-8 before being written. So your base64 string is being encoded before writing to the file so it’s not valid image data. You have to pass your image data as a Blob or an ArrayBuffer. Note this only works on iOS and Android. Have a look at Jeremy Banks’ b64toBlob function in this answer: https://stackoverflow.com/a/16245768

functionb64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = newArray(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = newUint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    var blob = newBlob(byteArrays, {type: contentType});
    return blob;
}

You can pass the resulting blob into the write method.

Solution 2:

You also have to take into account that you are getting a base64 encoded picture, so you cannot just save the as an images file an expect it to be a image.

So you have to Base64 decode that first before it will be an image. Maybe look at atob to do that https://developer.mozilla.org/en-US/docs/Web/API/Window.atob

Post a Comment for "Saving Dataurl(base64) To File On Phonegap (android)"