K
K
kbats2015-09-20 09:44:32
PHP
kbats, 2015-09-20 09:44:32

How to upload file to server via python 3.4?

How to upload file to server via python 3.4 using php handler?
I use this php handler

<?php  
 if(is_uploaded_file($_FILES["filename"]["tmp_name"]))
   {
     // Если файл загружен успешно, перемещаем его
     // из временной директории в конечную
     move_uploaded_file($_FILES["filename"]["tmp_name"], "".$_FILES["filename"]["name"]);
   } else {
      echo("Ошибка загрузки файла");
   }
?>

Through html the form is loaded, but not through python requests
Here is the python code:
import requests
files = {'test.txt': open('test.txt', 'rb')}
r = requests.post('http://kbats183.besaba.com/python/uploudfile.php', files=files)
print (r.status_code == requests.codes.ok)
print(r.text)

Please tell me why it doesn't work

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolay Baryshnikov, 2019-05-19
@p141592

There is an easier and more difficult option.
For easier:

import os
os.system("scp FILE [email protected]:PATH")
#e.g. os.system("scp foo.bar [email protected]:/path/to/foo.bar")

Only first you need to save the file to disk before sending
And more difficult:
import os
import paramiko

ssh = paramiko.SSHClient() 
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

This is the same, but without using the console command

Y
Yuri Iovkov, 2020-03-02
@Rurick80

Might be worth a try?

with open('test.txt', 'rb') as fd:
    files = {'uploadfile' : ('test.txt',  fd.read() ) }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question