Created
December 30, 2018 01:34
-
-
Save morficus/1a34660441a7ecd31310448fbfb6ce7e to your computer and use it in GitHub Desktop.
Helper functions for dealing with base64 encoded files
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
/** | |
* Helper function to properly handler downloading Blobs | |
* | |
* @param {String} blob Base64 encoded file | |
* @param {String} userFriendlyName The file name to be used when downloading the blob | |
*/ | |
export default function({ fileString, userFriendlyName }) { | |
const dataUri = `data:application/octet-stream;base64,${fileString}` | |
if (window.navigator.msSaveOrOpenBlob) { | |
// older versions of IE11 do not have proper support for download Blobs | |
// ref1: https://stackoverflow.com/a/24354303/1021300 | |
// ref2: https://msdn.microsoft.com/en-us/library/hh772332(v=vs.85).aspx | |
window.navigator.msSaveOrOpenBlob(dataUri, userFriendlyName) | |
} else { | |
let link = document.createElement('a') | |
link.href = dataUri | |
link.download = userFriendlyName | |
document.body.appendChild(link) | |
link.click() | |
link.remove() | |
} | |
} |
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
/** | |
* | |
* @param {File} file The File object that is to be encoded | |
* @returns {Promise<String>} Base64 representation | |
*/ | |
export default function(file) { | |
return new Promise((resolve, reject) => { | |
const reader = new FileReader() | |
reader.readAsDataURL(file) | |
reader.onload = function() { | |
let encoded = reader.result.replace(/^data:(.*;base64,)?/, '') | |
// ref: https://stackoverflow.com/questions/4080988/why-does-base64-encoding-require-padding-if-the-input-length-is-not-divisible-by | |
if (encoded.length % 4 > 0) { | |
encoded += '='.repeat(4 - (encoded.length % 4)) | |
} | |
resolve(encoded) | |
} | |
reader.onerror = function(error) { | |
console.log('Error: ', error) | |
reject(error) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment