如何使用AngularJS创建文件并将其保存到本地文件系统?

时间:2016-07-19 15:34:27

标签: javascript angularjs file

我想在将数据记录到文件之前创建并保存文件。以下方法是创建数据并将其保存到文件,并且只有Chrome浏览器支持。如何创建和保存空白文件,然后将数据记录到其中并支持IE和Chrome?

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

3 个答案:

答案 0 :(得分:15)

保存到文件系统

查看angular-file-saver

或者使用以下代码作为保存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
        }
    }

使用LocalStorage

保存到localStorage:

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

从localStorage获取

window.localStorage.getItem('key');

从localStorage中删除密钥

window.localStorage.removeItem('key');

或使用AngularJS模块'ngStorage'

浏览器兼容性

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

查看实时示例(@cOlz学分)

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

答案 1 :(得分:7)

$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) {

        });

成功部分需要打开本地系统,用户可以选择,保存文件的位置。在这里,我使用了<a>。我正在享受宁静的服务

答案 2 :(得分:0)

如何使用AngularJS(使用DEMO)在本地下载文件

使用带有<a>属性的download标签:

<a download="{{files[0].name}}" xd-href="data">
  <button>Download data</button>
</a>

xd-href指令:

app.directive("xdHref", function() {
  return function linkFn (scope, elem, attrs) {
     scope.$watch(attrs.xdHref, function(newVal) {
       newVal && elem.attr("href", newVal);
     });
  };
});

下载时,浏览器会提示用户一个可以接受或取消的对话框。有关更多信息,请参见MDN HTML Reference - <a> Tag

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>

另请参阅ng-model for <input type=“file”/> (with directive DEMO)