Is it possible to write data to a locally json file with nothing but angular?

后端 未结 5 554
不思量自难忘°
不思量自难忘° 2020-12-03 04:44

I\'m trying to write data to a json file after hitting \"Submit\" on an html formly-form using only angular, but nothing is happening. I know I can read a json file using an

相关标签:
5条回答
  • 2020-12-03 05:11

    You can't access the local filesystem (directly) from Javascript. This is enforced for security reasons (and makes sense when you think about it!).

    Local file access with javascript

    0 讨论(0)
  • 2020-12-03 05:19

    No.

    Angular runs client side.

    If you want to write data to the server (even one on the same computer as the browser) then you need server side code to do it.

    0 讨论(0)
  • 2020-12-03 05:21

    Since this is not possible you could try another route. Your $scope.save was not being invoked by the way, only assigned.

    $scope.save = function() {
      localStorage.model = JSON.stringify($scope.model);
    };
    function onSubmit() {
      $scope.save();
      $scope.msg = 'saved';
    };
    

    To get your model back do this on init:

    if (localStorage.model)
      $scope.model = JSON.parse(localStorage.model);
    
    0 讨论(0)
  • 2020-12-03 05:23

    The following code adds a download button for a JSON object.

    Note: wrapping a button with an anchor tag is not recommended for HTML 5 yet it works in Chrome which is all I needed. YMMV.

    HTML:

    <a download="my-json-object.json" [href]="dataUri">
      <button>Download</button>
    </a>
    

    Typescript:

      get dataUri(): SafeUrl {
        const jsonData = JSON.stringify(this.dataSource);
        const uri = 'data:application/json;charset=UTF-8,' + encodeURIComponent(jsonData);
        return this.sanitizer.bypassSecurityTrustUrl(uri);
      }
    
    0 讨论(0)
  • 2020-12-03 05:27

    Is it possible to write data to a locally json file with nothing but angular?

    No. Even if you're running the page from the local file system (e.g., file://myfile.html) or from a local webserver (e.g., http://localhost/myfile.html or http://host-on-my-intranet/myfile.html), you still have no means of directly writing to a file from browser-hosted JavaScript code.

    Two choices:

    1. Send it to something (e.g., a server) that can write it out, or

    2. Provide it as a data: URI (if feasible in your case) that the user can right-click and choose "save as..."

      Here's how you create a data: URI for some JSON text:

      var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
      

    Full Example of #2:

    var theData = {
      foo: "bar"
    };
    var theJSON = JSON.stringify(theData);
    var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
    
    var a = document.createElement('a');
    a.href = uri;
    a.innerHTML = "Right-click and choose 'save as...'";
    document.body.appendChild(a);

    0 讨论(0)
提交回复
热议问题