PHP如何接收Python上传的文件并存储到指定project文件夹
问题修复方案
核心错误原因
- Python端仅传递了文件名字符串,没有上传实际的文件内容:
requests.post只传了带文件名的post字段,没有携带本地txt文件的二进制数据,PHP端根本收不到文件本体。 - PHP端错误使用
move_uploaded_file()函数:该函数的第一个参数必须是HTTP上传产生的临时文件路径(保存在$_FILES全局变量中),你传入$_POST中的字符串参数完全不符合函数要求。 - 路径配置错误:
move_uploaded_file()的第二个参数需要是完整的目标文件路径,不能只传目录;Windows路径中的反斜杠需要转义或者直接用正斜杠避免解析错误。 - 权限&目录校验缺失:没有判断目标目录是否存在、是否有写入权限,权限不足也会导致写入失败。
修复后的代码
Python端代码
import subprocess import os import requests url = 'http://localhost:9090/project/php/test.php' driveStr = subprocess.check_output("fsutil fsinfo drives") driveStr = driveStr.decode("utf-8") driveStr = driveStr.strip().lstrip('Drives: ') drives = driveStr.split() print(drives) for drive in drives: if os.path.isdir(drive): # 加异常捕获跳过无法访问的系统目录 try: for root, dirs, files in os.walk(drive): for filename in files: if not filename.endswith(".txt"): continue # 拼接本地文件的完整绝对路径 full_file_path = os.path.join(root, filename) print(f"正在上传:{full_file_path}") # 读取本地文件,通过files参数传递文件内容 with open(full_file_path, 'rb') as f: post_data = {'filename': filename} response = requests.post(url, data=post_data, files={'upload_txt': f}) print(f"上传结果:{response.text}") except PermissionError: print(f"无权限访问目录{drive},已跳过")
PHP端代码
if(isset($_POST['filename']) && isset($_FILES['upload_txt'])) { // 目标目录用正斜杠,末尾加斜杠保证路径拼接正确 $dir = "C:/wamp64/www/project/"; // 目录不存在则自动创建 if (!file_exists($dir)) { mkdir($dir, 0777, true); } // 拼接完整的目标文件路径 $save_path = $dir . basename($_POST['filename']); // 移动上传的临时文件到目标路径 if (move_uploaded_file($_FILES['upload_txt']['tmp_name'], $save_path)) { echo "success:已保存到{$save_path}"; } else { echo "fail:" . print_r(error_get_last(), true); } } else { echo "参数缺失,请检查上传逻辑"; }
额外校验项
- 右键打开
C:/wamp64/www/project目录的属性,在安全选项卡中给WAMP运行用户(通常是apache/nginx的运行用户、NETWORK SERVICE)授予写入权限。 - 如果需要保留重名文件,可在文件名前拼接时间戳、随机字符串避免覆盖。
内容的提问来源于stack exchange,提问作者programmer
相关产品推荐
相关产品推荐

