Javascript 如何使用 AngularJS 创建文件并将其保存到本地文件系统?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38462894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create and save file to local fileSystem using AngularJS?
提问by hussain
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?
我想在将数据记录到文件之前创建并保存文件。下面的方法是创建和保存数据到文件,它只支持 Chrome 浏览器。如何创建和保存空白文件,然后将数据记录到其中并支持 IE 和 Chrome?
ctrl.js:
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')
}
回答by daan.desmedt
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.
或者使用以下代码作为保存 BLOB 的参考。从blob
对象生成JSON
对象的地方。但是提取到TEXT
文件也是可能的。
// 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
从 localStorage 获取
window.localStorage.getItem('key');
Delete key from localStorage
从本地存储中删除密钥
window.localStorage.removeItem('key');
Or using the AngularJS module 'ngStorage'
或者使用 AngularJS 模块“ngStorage”
Browser compatibility
浏览器兼容性
Chrome - 4
Firefox (Gecko) - 3.5
Internet Explorer - 8
Opera - 10.50
Safari (WebKit) - 4
See live example (credits to @cOlz)
查看实时示例(感谢@cOlz)
回答by Sangram Badi
$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
成功部分需要打开本地系统,用户可以通过它选择保存文件的位置。我在这里使用了<a>
. 我正在享受宁静的服务
回答by georgeawg
How to Download Files Locally with AngularJS (with DEMO)
如何使用 AngularJS 在本地下载文件(带 DEMO)
Use an <a>
tag with a download
attribute:
使用<a>
带有download
属性的标签:
<a download="{{files[0].name}}" xd-href="data">
<button>Download data</button>
</a>
The xd-href
Directive:
该xd-href
指令:
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
下载时,浏览器会提示用户一个可以接受或取消的对话框。有关更多信息,请参阅MDN HTML 参考 -<a>
标签
THE DEMO
演示
angular.module("app",[])
.controller("myVm", function($scope, $http, $window) {
var vm = $scope;
var url = "//httpbin.org/post";
var config = { headers: {"Content-Type": undefined} };
vm.upload = function() {
vm.spin = "Uploading...";
$http.post(url, vm.files[0], config).
then(function(response) {
vm.result = "SUCCESS";
vm.data = response.data.data;
}).catch(function(response) {
vm.result = "ERROR "+response.status;
}).finally(function() {
vm.spin = undefined
});
};
})
.directive("xdHref", function() {
return function linkFn (scope, elem, attrs) {
scope.$watch(attrs.xdHref, function(newVal) {
newVal && elem.attr("href", newVal);
});
};
})
.directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
});
}
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="myVm">
<h2>Upload and Download File with AngularJS</h2>
<input type="file" select-ng-files ng-model="files">
<br>
<code>
Name: {{files[0].name}}<br>
Size: {{files[0].size}}<br>
Type: {{files[0].type}}<br>
Date: {{files[0].lastModifiedDate}}<br>
</code>
<button ng-click="upload()" ng-disabled="!files">
Upload
</button>
<span ng-show="spin">{{spin}}</span>
<span ng-show="result">{{result}}</span>
<a download="data_{{files[0].name}}" xd-href="data">
<button ng-disabled="!data">Download data</button>
</a>
</body>
See also ng-model for <input type=“file”/>
(with directive DEMO)