htmltypescripthtml5-filesystem

Trying to create a text file using TS and HTML5


In my app I'm receiving a string which needs to be saved to the local machine. I', reading this guide (html5 filesystem tutorial). The problem I have to use TS ("typescript": "2.6.1") and looks like part of the API is not supported. The following line gives me two errors:

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

first:

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

second:

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

Any workaround or an updated documentation? PS I'm aware this is supported only in Chrome.


Solution

  • This API is currently only supported in Chrom and does not work in other browsers. If you are using Chrome however, you have to use the prefixed version of this function which is webkitRequestFileSystem:

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

    The support also goes for window.TEMPORARY.

    Now, if you want to create a file and write some content in it, you have to create a so-called writer object:

    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);
    

    For more information on the FileSystemFileEntry API check out this link.