How to use base64 encoding on HTML5 Blob object

Exos picture Exos · Jan 19, 2015 · Viewed 9.4k times · Source

I'm building a library to "nodeize" the HTML5 File Api (currently in alpha)[0], to make it work with binary contents and don't have problems with charsets, I'm using Buffer[1] utility.

But the HTML5 File API uses Blob native object. Actualy I'm using the type 'application/octet-stream', and 'binary' from Buffer encoding. But, I want to use base64 in order to prevent any problem:

CoFS.prototype.writeFile = function (fileName, data, encoding, callback) {

    var self = this;

    if (Buffer.isBuffer(data)) {
        callback = encoding;
        encoding = undefined;
    } else {
        data = new Buffer(data, encoding);
    }

    this._ifready(function () {

        self.getFileEntry(fileName, {create: true, exclusive: true}, function (err, fileEntry) {

            if (err) return callback(new Error("Error getting file access " + err.message));

            fileEntry.createWriter(function(fileWriter) {

                fileWriter.onwriteend = function () {
                    callback(null);
                };

                fileWriter.onerror = function(e) {
                    callback(new Error(e.toString()));
                };

                var blob = new Blob([data.toString('binary')], {type: 'application/octet-stream'});

                fileWriter.write(blob);

            }, function () {
                callback(new Error('Error writing ' + fileName));
            }); 
        });

    });

};

Exacts on:

var blob = new Blob([data.toString('binary')], {type: 'application/octet-stream'});

I red the MDN page[2] but I didn't see anything about the encoding.

Is there any way to accomplish something like that?:

var blob = new Blob([data.toString('base64')], {type: 'application/octet-stream', encoding: 'base64'});

Thankyou.

Answer

Exos picture Exos · Jan 20, 2015

I realized the Buffer object is extended from Int8Array, and both are compatible.

My code now is:

var blob = new Blob(
    [data], // Data is a buffer!
    {
        type: 'application/octet-stream'
    }
);

fileWriter.write(blob);

And for read, I use readAsArrayBuffer method, you can do:

var d = new Int8Array(arr); // When arr is arrayBuffer
var buf = new Buffer(d); // And works!

This solve my problem. For convert base64 encoded content and use in a blob, with Buffer, can be:

var blob = new Blob(
    [new Buffer(cleanData, 'base64')],
    {
        type: 'application/octet-stream'
    }
);