While working with binary files, I discovered that:
- If it's a text-based file, I need to use data:text/plain;charset=utf-8,
- and if it's a multimedia file, I should use data:image/png;base64,
I attempted to use base64 encoding and encountered an error when trying to download a file using the following syntax.
<a href="data:text/plain;base64,VGVzdCBEb2N1bWVudA%3D%1E" download="sample text.txt">download</a>
The script used to generate the above code is as follows:
<script>
var filecontent = binaryAgent("010101100100011101010110011110100110010001000011010000100100010101100010001100100100111000110001011000100101011101010110011101010110010001000001001111010011110");
download("sample text.txt", filecontent, "data:text/plain;base64,");
function binaryAgent(str) {
// Removes the spaces from the binary string
str = str.replace(/\s+/g, '');
// Pretty (correct) print binary (add a space every 8 characters)
str = str.match(/.{1,8}/g).join(" ");
var binString = '';
str.split(' ').map(function(bin) {
binString += String.fromCharCode(parseInt(bin, 2));
});
return binString;
}
function download(filename, text, encodedType) {
var element = document.createElement('a');
element.setAttribute('href', encodedType + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
</script>
What makes these two types different? Can base64 be used for text-based files as well?