This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:
/**_x000D_
* Save a text as file using HTML <a> temporary element and Blob_x000D_
* @author Loreto Parisi_x000D_
*/_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
var downloadLink = document.createElement("a");_x000D_
downloadLink.download = fileName;_x000D_
if (window.webkitURL != null) {_x000D_
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
} else {_x000D_
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
downloadLink.onclick = document.body.removeChild(event.target);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
}_x000D_
downloadLink.click();_x000D_
} else { // Alternative 2: using Data_x000D_
var pp = document.createElement('a');_x000D_
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
encodeURIComponent(fileContents));_x000D_
pp.setAttribute('download', fileName);_x000D_
pp.onclick = document.body.removeChild(event.target);_x000D_
pp.click();_x000D_
}_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
The function is called like saveAsFile('out.json', jsonString);
. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL
.
In the else
, it is possible to see the same result obtained via the href
element plus the Data API, but this has several limitations that the Blob API has not.