'目录不存在: ' . $directory]); exit; } $files = scandir($directory); // 过滤掉 . 和 .. $files = array_diff($files, array('.', '..')); echo json_encode(['files' => array_values($files)]); break; // 读取文件内容 case 'read': if (empty($file)) { echo json_encode(['error' => '文件名为空']); exit; } $filePath = __DIR__ . '/' . $file; // 添加调试输出 if (!file_exists($filePath)) { echo json_encode(['error' => '文件不存在', 'file' => $file, 'filePath' => $filePath]); exit; } // 如果文件存在,读取内容并保证内容是 UTF-8 编码 $content = file_get_contents($filePath); $content = mb_convert_encoding($content, 'UTF-8', 'auto'); // 强制转换为 UTF-8 编码 echo json_encode(['status' => 'success', 'content' => $content]); break; // 保存文件 case 'save': $data = json_decode(file_get_contents('php://input'), true); $filename = $data['filename'] ?? ''; $content = $data['content'] ?? ''; if (empty($filename)) { echo json_encode(['error' => '文件名不能为空']); exit; } // 强制转换内容为 UTF-8 编码 $content = mb_convert_encoding($content, 'UTF-8', 'auto'); // 强制转换为 UTF-8 编码 $filePath = __DIR__ . '/' . $filename; file_put_contents($filePath, $content); // 保存文件内容 echo json_encode(['message' => '文件保存成功']); break; // 删除文件 case 'delete': $data = json_decode(file_get_contents('php://input'), true); $filename = $data['filename'] ?? ''; if (empty($filename)) { echo json_encode(['error' => '文件名不能为空']); exit; } $filePath = __DIR__ . '/' . $filename; if (file_exists($filePath)) { unlink($filePath); // 删除文件 echo json_encode(['message' => '文件已删除']); } else { echo json_encode(['error' => '文件不存在']); } break; // 下载文件 // 下载文件 // 下载文件 // 下载文件 // 下载文件 case 'download': $file = $_GET['file'] ?? ''; // 获取文件名 if (empty($file)) { echo json_encode(['error' => '文件名为空']); // 如果文件名为空,返回错误信息 exit; } $filePath = __DIR__ . '/' . $file; // 文件的完整路径 if (file_exists($filePath)) { // 设置响应头,告诉浏览器这是一个文本文件,并且编码为 UTF-8 header('Content-Type: text/plain; charset=UTF-8'); // 设置文件下载的名称 header('Content-Disposition: attachment; filename="' . basename($file) . '"'); // 设置文件内容的长度 header('Content-Length: ' . filesize($filePath)); // 读取文件内容并输出给浏览器 readfile($filePath); exit; } else { // 如果文件不存在,返回错误信息 echo json_encode(['error' => '文件不存在']); } break; default: echo json_encode(['error' => '无效的操作']); } ?>