简体   繁体   中英

python - upload a file using POST

I am running a python on one server and looking to upload some files to a second server. When I run my python script, the files do not move across to the second server though.

The Python code for the script on the first server is:

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)

The code for the incoming.php on the second server is:

    $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);
    }
?>

The entire directory structure and all files on the second server are owned by www-data. The response code I get when running the script on the first server is '500 Internal Server Error'. I'm using Python 2.7 on Ubuntu 18.04 on the first server, and LAMP stack on Ubuntu 18.04 on the second server.

OK, I pared the code back and have gotten it to work successfully. The working code is:

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

and the PHP code on the server side (/var/www/html) is:

<?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)
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM