亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python - 使用POST上傳文件

python - 使用POST上傳文件

PHP
胡說叔叔 2022-07-29 16:48:07
我在一臺服務器上運行 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)

?>


查看完整回答
反對 回復 2022-07-29
  • 1 回答
  • 0 關注
  • 369 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號