Python requests模块向PHP脚本发送POST请求
我需要把一些 .csv 文件上传到一个自签名的 HTTPS Apache 服务器上。我的 HTTPS 服务器是用 PHP 运行的,而我的客户端则是用 Python 脚本把文件 POST 到这个 HTTPS 服务器上。PHP.ini 文件里设置了上传文件和 POST 最大大小为 20M,而且没有多余的空格。我需要上传的文件只有 4KB。
我的 Python 脚本:
import requests
username = "user"
password = 'password'
myfile = "/full/path/to/myfile.csv"
url = "https://www.mydomain.com/file_upload.php"
files = {'file': open(myfile, 'rb')}
r = requests.post(url, files=files, auth=(username, password), verify=False)
print r.text
print r.status_code
我收到了状态码 200,但文件并没有出现在目标服务器上。我觉得问题出在我的 file_upload.php 文件里。
$_FILES['userfile']['name'] 是我在用 HTML 表单上传文件时使用的名字,但现在不是这种情况了。我觉得我对 PHP 中的 $_FILES 变量理解得不够,所以不太明白当不通过表单上传时,文件的 ID 应该是什么样的?
<?php
$uploaddir = '/var/www/html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['file-id']['name']);
move_uploaded_file($_FILES['file-id']['tmp_name'], $uploadfile);
error_log(print_r($_FILES['file-id']['error']), 3, $error_log_file);
?>
我的 Apache 错误日志报告了以下 PHP 提示
[2014年6月5日 星期四 09:35:19.120760] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 警告:在未知的第 0 行中,multipart/form-data POST 数据缺少边界
[2014年6月5日 星期四 09:35:19.124625] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 提示:在 /var/www/html/file_upload.php 的第 8 行中,未定义索引:file
[2014年6月5日 星期四 09:35:19.124673] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 提示:在 /var/www/html/file_upload.php 的第 11 行中,未定义索引:file
[2014年6月5日 星期四 09:35:19.124686] [:error] [pid 8030] [client xxx.xxx.xxx.xxx:49207] PHP 提示:在 /var/www/html/file_upload.php 的第 12 行中,未定义索引:file
权限
我的 www 文件夹的权限是 chown -R www-data.www-data
1 个回答
这里是解决方案:
当你想用Python的requests模块上传一个文件时,可以这样读取文件:
files = {'testname': open(myfile, 'rb')}
然后在接收文件的PHP文件中,必须这样使用$_FILES变量:
$uploadfile = $uploaddir . basename($_FILES['testname']['name']);
move_uploaded_file($_FILES['testname']['tmp_name'], $uploadfile);
简单来说,$_FILES这个索引的名字就是你在Python中读取文件名时给的标签名称。