Skip to content

Instantly share code, notes, and snippets.

@sashadev-sky
Last active May 20, 2020 19:13
Show Gist options
  • Save sashadev-sky/f84093957395363e7fadf0fb18c98c24 to your computer and use it in GitHub Desktop.
Save sashadev-sky/f84093957395363e7fadf0fb18c98c24 to your computer and use it in GitHub Desktop.
// Specifically, as data url
var saveBlobAsFile = function(fileName, fileContents) {
if (typeof(Blob) != 'undefined') { // using Blob
var textFileAsBlob = new Blob([fileContents], {
type: 'text/plain'
});
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
if (window.webkitURL != null) {
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = document.body.removeChild(event.target);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
} else {
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.onclick = document.body.removeChild(event.target);
pp.click();
}
} //saveBlobAsFile
var jsonObject = {
"name": "John",
"age": 31,
"city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";
saveBlobAsFile(fileName, fileContents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment