如何使用AngularJS创建文件并将文件保存到本地文件系统? [英] How to create and save file to local fileSystem using AngularJS?

查看:376
本文介绍了如何使用AngularJS创建文件并将文件保存到本地文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想先创建并保存文件,然后再将数据登录到其中.以下方法是创建数据并将其保存到文件的方法,仅Chrome浏览器支持.如何创建和保存空白文件,然后将数据登录到其中并具有IE和Chrome支持?

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')
}

推荐答案

保存到文件系统

看看 angular-file-saver

或在保存BLOB时使用以下代码作为参考. blob对象是从JSON对象生成的.但是也可以将其提取到TEXT文件中.

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
        }
    }

使用LocalStorage

保存到localStorage:

Saving to localStorage:

window.localStorage.setItem('key', value);

从localStorage获取

Getting from localStorage

window.localStorage.getItem('key');

从localStorage删除密钥

Delete key from localStorage

window.localStorage.removeItem('key');

或使用AngularJS模块'ngStorage'

Or using the AngularJS module 'ngStorage'

浏览器兼容性

Chrome - 4    
Firefox (Gecko) - 3.5    
Internet Explorer - 8    
Opera - 10.50    
Safari (WebKit) - 4

查看实时示例(@cOlz的积分)

https://codepen.io/gMohrin/pen/YZqgQW

这篇关于如何使用AngularJS创建文件并将文件保存到本地文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆