How to create and save file to local fileSystem using AngularJS?
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)
$http({ method : 'GET', url : $scope.BASEURL + 'file-download?fileType='+$scope.selectedFile, responseType: 'arraybuffer', headers : { 'Content-Type' : 'application/json' } }).success(function(data, status, headers, config) { // TODO when WS success var file = new Blob([ data ], { type : 'application/json' }); //trick to download store a file having its URL var fileURL = URL.createObjectURL(file); var a = document.createElement('a'); a.href = fileURL; a.target = '_blank'; a.download = $scope.selectedFile+'.json'; document.body.appendChild(a); a.click(); }).error(function(data, status, headers, config) { });
In success part need to open local system, by which the user can choose, where to save file. Here I have used <a>
. And I am hitting restful service
How to Download Files Locally with AngularJS (with DEMO)
Use an <a>
tag with a download
attribute:
<a download="{{files[0].name}}" xd-href="data"> <button>Download data</button></a>
The xd-href
Directive:
app.directive("xdHref", function() { return function linkFn (scope, elem, attrs) { scope.$watch(attrs.xdHref, function(newVal) { newVal && elem.attr("href", newVal); }); };});
When downloading, browsers prompt user with a dialog that can be accepted or cancelled. For more information, see MDN HTML Reference - <a>
Tag
THE DEMO
See also ng-model for <input type=“file”/>
(with directive DEMO)