藉助第三方庫:Requests
php
其官網地址:html
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:python
<?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文件內新增:git