我在一臺服務器上運行 python 并希望將一些文件上傳到第二臺服務器。當我運行我的 python 腳本時,文件不會移動到第二臺服務器。第一臺服務器上腳本的 Python 代碼是:url = 'https://www.example.com/incoming.php'for x in list: if os.path.exists(x): filename = os.path.abspath(x) #get the full path of a file new_name = filename.replace('/', '_') #replace the / with _ new_name_zip = new_name + '.zip' shutil.copy(x, new_name) #copy the file and give it a new name zippy = zipfile.ZipFile(new_name_zip, 'w', zipfile.ZIP_DEFLATED) zippy.write(new_name) os.remove(new_name) #remove the unzipped file uploadFile = {'uploadFile': (new_name_zip, open(new_name_zip, 'rb'))} r = requests.post(url, files=uploadFile) print (r.status_code) print (r.reason)第二臺服務器上的incoming.php 的代碼是: $name=$_FILES['uploadFile']['name']; $size=$_FILES['uploadFile']['size']; $type=$_FILES['uploadFile']['type']; $tmp_name=$_FILES['uploadFile']['tmp_name']; $error=$_FILES['uploadFile']['error']; $location='uploads/'; if(move_uploaded_file($tmp_name, $location.$name)) { $myfile = fopen("newfile.txt", "w"); $txt = "Success\n"; fwrite($myfile, $txt); fclose($myfile); }?>第二臺服務器上的整個目錄結構和所有文件都歸 www-data 所有。我在第一臺服務器上運行腳本時得到的響應代碼是“500 Internal Server Error”。我在第一臺服務器上的 Ubuntu 18.04 上使用 Python 2.7,在第二臺服務器上的 Ubuntu 18.04 上使用 LAMP 堆棧。
1 回答

溫溫醬
TA貢獻1752條經驗 獲得超4個贊
好的,我削減了代碼并使其成功運行。工作代碼是:
#!/usr/bin/python3
import requests
url = 'http://example.com/receiver.php'
filename = 'file.txt'
up = {'uploadedFile':(filename, open(filename, 'rb'), 'multipart/form-data')}
r = requests.post(url, files=up)
print (str(r.status_code) + ' ' + r.reason)
服務器端的 PHP 代碼(/var/www/html)是:
<?php
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$uploadFileDir = 'uploads/';
$dest_path = $uploadFileDir . $fileName;
move_uploaded_file($fileTmpPath, $dest_path)
?>
- 1 回答
- 0 關注
- 369 瀏覽
添加回答
舉報
0/150
提交
取消