简体   繁体   English

将JSON对象另存为AngularJS中的文件

[英]Saving a JSON object as a file in AngularJS

I wanted to know if there was any way to save a JSON object as a .json file in the project directory. 我想知道是否有任何方法可以将JSON对象另存为项目目录中的.json文件。 I have a form and each time a user fills it, I want the JSON file to be appended. 我有一个表单,每次用户填写时,我都希望附加JSON文件。 I'm currently using AngularJS only. 我目前仅使用AngularJS。

AngularJS is just JavaScript, so use any methods that let you save files with JS ( it's better to do it with backend like PHP ). AngularJS只是JavaScript,因此请使用任何允许您使用JS保存文件的方法( 最好使用PHP之类的后端来保存文件)。 One of such methods is FileSaver.js (uses HTML5 features). 其中一种方法是FileSaver.js (使用HTML5功能)。

Here is a working demo: 这是一个工作示例:

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.myJSON = { "A": "B" }; $scope.saveJSON = function(json) { var jsonse = JSON.stringify(json); var blob = new Blob([jsonse], { type: "application/json" }); $scope.filename = $scope.filename || "my_json"; saveAs(blob, $scope.filename + ".json"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> Some JSON: <pre> {{myJSON | json}} </pre> File Name: <input type="text" ng-model="filename" /><br> <button ng-click="saveJSON(myJSON)">Save</button> </div> 

OR you can send a request to the backend like PHP with 或者您可以使用以下方式将请求发送到后端,例如PHP

$http.post("createJSON.php",json).then((res)=>{...}, (err)=>{...})

And receive with: 并收到:

<?php
$dataReceived = file_get_contents('php://input');
$myFile = json_decode( $dataReceived );

$path = $myFile->path; // path to store it in
$name = $myFile->name; // file name
$JSON = $myFile->json; // content

# Storing file
$file = fopen($path.$name.".json", 'w');
fwrite($file, $JSON);
fclose($file);
?>

you can't save files to the disk just with javascript. 您不能仅使用javascript将文件保存到磁盘。 maybe you really need nodejs,and use the fs module. 也许您确实需要nodejs,并使用fs模块。 Is it possible to write data to file using only JavaScript? 是否可以仅使用JavaScript将数据写入文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM