首页 > 解决方案 > 尝试使用 TS 和 HTML5 创建文本文件

问题描述

在我的应用程序中,我收到了一个string需要保存到本地机器的信息。我,正在阅读指南(html5 文件系统教程)。我必须使用 TS ("typescript": "2.6.1") 并且看起来部分 API 不受支持的问题。以下行给了我两个错误:

  window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, this.errorHandler);

第一的:

[ts] Property 'requestFileSystem' does not exist on type 'Window'.

第二:

[ts] Property 'TEMPORARY' does not exist on type 'Window'.

任何解决方法或更新的文档?PS 我知道这仅在 Chrome 中受支持。

标签: htmltypescripthtml5-filesystem

解决方案


此 API 目前仅在 Chrom 中支持,在其他浏览器中不起作用。但是,如果您使用的是 Chrome,则必须使用此功能的前缀版本,即webkitRequestFileSystem

var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

支持也适用window.TEMPORARY

现在,如果你想创建一个文件并在其中写入一些内容,你必须创建一个所谓的 writer 对象:

function onInitFs(fs) {
  fs.root.getFile('my-file.txt', {create: true}, function(fileEntry) {
    fileEntry.createWriter(function(fileWriter) {
      fileWriter.onwriteend = function(e) {
        ...
      };

      fileWriter.onerror = function(e) {
        ...
      };

      var blob = new Blob(['Content that goes into the file'], {type: 'text/plain'});

      fileWriter.write(blob);
    }, errorHandler);
  }, errorHandler);
}

requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);

有关FileSystemFileEntryAPI 的更多信息,请查看此链接


推荐阅读