python3 post方式上传文件。

时间:2024-02-21 18:12:59

借助第三方库:Requests

其官网地址:

 
 
 
 
官网上写的安装方式:http://docs.python-requests.org/en/latest/user/install/#install
 
最终安装实现的方式:
控制台下通过cd命令切换路径到,下载后解压到的路径:
python  setup.py install
 
 
上代码,如下:
 
Python上传的代码:
import requests
 
url = \'http://www.test.com/doFile.php\'
#url = \'http://www.test.com/doPost.php\'
#files = {\'file\': open(\'D:/tmp/1.jpg\', \'rb\')}

# 要上传的文件
files = {\'file123\': (\'1.jpg\', open(\'D:/tmp/1.jpg\', \'rb\'))
        }     #显式的设置文件名
            
# post携带的数据            
data = {\'a\':\'杨\',\'b\':\'hello\'}

 
r = requests.post(url, files=files, data = data)
print(r.text)

 

PHP的doFile.php:

<?php 

header("content-type:text/html;charset=utf-8");
date_default_timezone_set("PRC");

$pImg=$_FILES[\'file123\'];

//echo json_encode($pImg);
//echo \'\n<br>\';

//echo json_encode($_FILES);
//echo \'\n<br>\';

//echo \'_REQUEST\';
//echo json_decode($_REQUEST);
//echo \'\n<br>\';
//print_r($pImg);

$request_arg = \'request,:\';
$request_arg .= json_encode($pImg);

foreach ($_REQUEST as $key => $value) 
{
	$request_arg .=  $key.\'=\'.$value.",";
}
$request_arg .=  "\n";
	
$myfile = fopen("file.txt", "a") or die("Unable to open file!");
fwrite($myfile, $request_arg);
fclose($myfile);

if($pImg[\'error\']==UPLOAD_ERR_OK)
{
  //取得扩展名
  $extName=strtolower(end(explode(\'.\',$pImg[\'name\'])));
  $filename=date("Ymdhis").".".$extName;
  $dest="uploads/".$filename;
  move_uploaded_file($pImg[\'tmp_name\'],$dest);
  echo "上传成功";
}
else
{
  echo "上传错误";
}
?>

 

 

上传一次后file.txt文件内新增: