【问题标题】:python - upload a file using POSTpython - 使用 POST 上传文件
【发布时间】:2020-05-11 06:45:10
【问题描述】:

我在一台服务器上运行 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 堆栈。

【问题讨论】:

    标签: python php python-2.7 post


    【解决方案1】:

    好的,我将代码剪掉并让它成功运行。工作代码是:

    #!/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)
    ?>
    

    【讨论】:

      猜你喜欢
      • 2012-06-18
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 2021-08-28
      • 2017-12-06
      相关资源
      最近更新 更多