epub.js icon indicating copy to clipboard operation
epub.js copied to clipboard

Load epub from base 64 format

Open maxiplay opened this issue 7 years ago • 4 comments

I'm storing epub and others file in base 64 from differents reasons. I want to be able to load epub directly from base 64 and not use file system or server. (Like image base 64 based via src attribute)

It seems it does not work and crash when I try ePubReader(base64Value);

Do you have information about it ?

maxiplay avatar Mar 23 '18 13:03 maxiplay

Try this: ePubReader("data:application+zip;base64," + base64Value)

pgaskin avatar Mar 23 '18 14:03 pgaskin

My base64Value variable already contains "data:application/epub+zip;base64,..."

For now I transform base64 to blob, then to arraybuffer and it works but it's not very a best.


  function onSuccess(arrayBuffer) {
                            that.$.documentEpubViewer.path = arrayBuffer;
                       }

that.$.fileUtil.dataURItoArrayBuffer(newValue, onSuccess);


   dataURItoBlob: function (dataURI) {
                    // convert base64 to raw binary data held in a string
                    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
                    var byteString = atob(dataURI.split(',')[1]);

                    // separate out the mime component
                    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                    // write the bytes of the string to an ArrayBuffer
                    var ab = new ArrayBuffer(byteString.length);
                    var ia = new Uint8Array(ab);
                    for (var i = 0; i < byteString.length; i++) {
                        ia[i] = byteString.charCodeAt(i);
                    }

                    //New Code
                    return new Blob([ab], {type: mimeString});


                },


                dataURItoArrayBuffer: function (dataURI, successCallback) {

                    var blob = this.dataURItoBlob(dataURI);

                    var fileReader = new FileReader();
                    fileReader.onload = function () {

                        successCallback(this.result);

                    };
                    fileReader.readAsArrayBuffer(blob);


                }

maxiplay avatar Mar 23 '18 15:03 maxiplay

@maxiplay I think that is the best way to do it then. The only improvement I can think of is if you use the new fetch API to reduce the amount of code to about 2-3 lines (fetch the data url, convert to blob, get blob).

pgaskin avatar Mar 23 '18 19:03 pgaskin

Can you try passing the encoding?

let book = new ePub("file.epub", ({ encoding: "base64" });

fchasen avatar May 18 '18 07:05 fchasen