Create downloadable file
by justinwyllie
HTML
<div>
<textarea id="game_data"></textarea>
<button id="save_game_data">Save</button>
<!-- or use an img tag and set its src -->
<a id="file" src="" download="HexagonData.dat" width="200" height="100" border="0" style="border-width:0px">Get Your Game Data</a>
</div>
<!--
HQU1EQVQ
Ij5HQU1EQVQ8 -> ">GAMDAT<
"> -> Ij4=
< -> PA==
-->
CSS
div * {
display: block;
}
#file {
display: none;
}
JavaScript
jQuery(function($) {
$("#save_game_data").click(function() {
//TODO valid json?
//var gd = $.parseJSON(game_data);
//TODO it needs at least 4 entered chars
var game_data = $('#game_data').val();
var l = game_data.length; //number of chars not bytes
console.log(l);
//it must be 3 bytes
//so this will only work with single byte encodings eg latin-1
var short = l % 3 ;
if (short == 1) {
game_data+= '--';
}
if (short == 2) {
game_data+= '-';
}
console.log(game_data);
//btoa() only works with latin-1 anyway
coded = btoa('">' + game_data + '<');
console.log(coded);
picPackage = pic1 + coded + pic2;
file = document.getElementById("file")
file.setAttribute("href", 'data:image/jpg;base64, ' + picPackage);
$('#file').show();
// file.setAttribute("src", 'data:image/jpg;base64, ' + picPackage)
//if the a and href doesn't work change the <a to an img tag and set the data into its src. you will lose the ability to set the filename
})
pic1...