Client-side file generation and download
Generate file content in the browser and download as a file.
by hansenmc
HTML
<a href="#download">download KML</a>
JavaScript
var isIE10 = false;
/*@cc_on
if (/^10/.test(@_jscript_version)) {
isIE10 = true;
}
@*/
function downloadFile(content, fileType, fileName) {
var type = 'data:' + fileType + ';charset=UTF-8';
var file = new Blob([content], { type: fileType });
if (isIE10) {
window.navigator.msSaveOrOpenBlob(file, fileName);
} else {
var downloadLink = window.document.createElement('a');
downloadLink.href = window.URL.createObjectURL(file);
downloadLink.download = fileName; //filename for download
// Append anchor to body.
document.body.appendChild(downloadLink);
downloadLink.click();
// Remove anchor from body
document.body.removeChild(downloadLink);
}
}
var fileType = 'application/vnd.google-earth.kml+xml';
var fileName = 'sample.kml';
var kml = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"><Placemark><name>Simple placemark</name><description>Attached to the ground. Intelligently places itself at the height of the underlying terrain.</description><Point><coordinates>-122.0822035425683,37.42228990140251,0</coordinates></Point> </Placemark></kml>';
$('a').click(function () {
downloadFile(kml, fileType, fileName);
});