I want to create and save file before I log data into it. The method below is creating and saving data to file and it is only supported by Chrome browser. How can I create and save blank file and then log data into it and has IE and Chrome support?
ctrl.js:
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
$scope.recordLogs = function(){
download('file text', 'myfilename.txt', 'text/plain')
}
Save to filesystem
Have a look at angular-file-saver
Or use the following code as a reference in saving a BLOB. Where the blob
object is generated from a JSON
Object. But extration to a TEXT
file is also possible.
// export page definition to json file
$scope.exportToFile = function(){
var filename = 'filename'
var blob = new Blob([angular.toJson(object, true)], {type: 'text/plain'});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else{
var e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
// window.URL.revokeObjectURL(a.href); // clean the url.createObjectURL resource
}
}
Using LocalStorage
Saving to localStorage:
window.localStorage.setItem('key', value);
Getting from localStorage
window.localStorage.getItem('key');
Delete key from localStorage
window.localStorage.removeItem('key');
Or using the AngularJS module 'ngStorage'
Browser compatibility
Chrome - 4
Firefox (Gecko) - 3.5
Internet Explorer - 8
Opera - 10.50
Safari (WebKit) - 4
See live example (credits to @cOlz)
https://codepen.io/gMohrin/pen/YZqgQW
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With