Created
September 11, 2013 10:19
-
-
Save Hagith/6521777 to your computer and use it in GitHub Desktop.
blob <-> base64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." ; | |
var blob = new Blob([data], { | |
type : "text/plain" | |
//type : "text/plain; charset=x-user-defined" | |
//type : "text/plain; charset=utf8" | |
}); | |
blobToBase64(blob, function(b64) { // convert BLOB to BASE64 | |
var newBlob = base64ToBlob(b64) ; // convert BASE64 to BLOB | |
$('body').html(blob.size + " != " + newBlob.size) ; | |
}); | |
// source: http://jsperf.com/blob-base64-conversion | |
function base64ToBlob(base64) { | |
var binary = atob(base64); | |
var len = binary.length; | |
var buffer = new ArrayBuffer(len); | |
var view = new Uint8Array(buffer); | |
for ( var i = 0; i < len; i++) { | |
view[i] = binary.charCodeAt(i); | |
} | |
var blob = new Blob([ view ]); | |
return blob; | |
}; | |
function blobToBase64(blob, cb) { | |
var reader = new FileReader(); | |
reader.onload = function() { | |
var dataUrl = reader.result; | |
var base64 = dataUrl.split(',')[1]; | |
cb(base64); | |
}; | |
reader.readAsDataURL(blob); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment