futurepress / epub.js

Enhanced eBooks in the browser.
http://futurepress.org
Other
6.4k stars 1.1k forks source link

Load epub from base 64 format #731

Open maxiplay opened 6 years ago

maxiplay commented 6 years ago

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 ?

pgaskin commented 6 years ago

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

maxiplay commented 6 years ago

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);

                }
pgaskin commented 6 years ago

@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).

fchasen commented 6 years ago

Can you try passing the encoding?

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