Created
July 10, 2019 03:22
-
-
Save mattlockyer/0e93cd218b36b038061d02659e1feca5 to your computer and use it in GitHub Desktop.
base 64 conversions using file reader and fetch
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
//FROM HERE: https://stackoverflow.com/a/54123275/1060487 | |
// base64 to buffer | |
function base64ToBufferAsync(base64) { | |
var dataUrl = "data:application/octet-binary;base64," + base64; | |
fetch(dataUrl) | |
.then(res => res.arrayBuffer()) | |
.then(buffer => { | |
console.log("base64 to buffer: " + new Uint8Array(buffer)); | |
}) | |
} | |
// buffer to base64 | |
function bufferToBase64Async( buffer ) { | |
var blob = new Blob([buffer], {type:'application/octet-binary'}); | |
console.log("buffer to blob:" + blob) | |
var fileReader = new FileReader(); | |
fileReader.onload = function() { | |
var dataUrl = fileReader.result; | |
console.log("blob to dataUrl: " + dataUrl); | |
var base64 = dataUrl.substr(dataUrl.indexOf(',')+1) | |
console.log("dataUrl to base64: " + base64); | |
}; | |
fileReader.readAsDataURL(blob); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment