如何将JSON字符串导出存储到树莓派Apache服务器的本地文件
实现方案(零复杂依赖,新手易操作)
前置准备
首先确认你的Apache已经启用PHP支持,树莓派终端执行以下命令安装即可:sudo apt update && sudo apt install libapache2-mod-php -y
安装完重启Apache生效:sudo systemctl restart apache2
步骤1:创建后端接收写文件的PHP脚本
在你的Apache站点根目录(默认是/var/www/html)新建一个save_json.php文件,内容如下,注释已经标注每一步作用:
<?php // 接收前端传过来的JSON内容和文件名 $json_content = $_POST['json_data']; $file_name = $_POST['file_name'] ? $_POST['file_name'] : 'default.json'; // 指定你要存在树莓派本地的目录,这里默认用站点根目录下的json_storage文件夹,你可以自行修改 $save_dir = '/var/www/html/json_storage/'; // 如果目录不存在就自动创建 if (!file_exists($save_dir)) { mkdir($save_dir, 0775, true); } // 拼接完整的保存路径 $full_path = $save_dir . $file_name; // 写文件 if (file_put_contents($full_path, $json_content)) { echo "保存成功,文件路径:" . $full_path; } else { echo "保存失败,请检查目录权限"; } ?>
步骤2:给保存目录设置权限
终端执行以下命令,给Apache运行用户开放目录读写权限,避免写入失败:
sudo mkdir /var/www/html/json_storage sudo chown -R www-data:www-data /var/www/html/json_storage sudo chmod -R 775 /var/www/html/json_storage
步骤3:修改前端代码,替换原下载逻辑
把你原来的download调用逻辑换成下面的fetch请求代码即可:
// 原来的调用逻辑:download(JSON.stringify(data, null, 2), 'json.txt', 'text/plain'); // 替换为以下内容 fetch('save_json.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: 'json_data=' + encodeURIComponent(JSON.stringify(data, null, 2)) + '&file_name=json.txt' }) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.error('出错了:', error));
验证方法
在网页触发保存逻辑后,直接打开树莓派的文件管理器,进入/var/www/html/json_storage目录就能看到保存的JSON文件。如果需要同时保留原有的客户端下载功能,在fetch请求后再加原来的download调用即可,两个功能可以共存。
内容的提问来源于stack exchange,提问作者oHeckGage
相关产品推荐
相关产品推荐

