[PageD'Accueil] [IndexDesTitres] [IndexDesTermes

Comme j'ai un peu galéré pour trouver une classe python pour uploader des fichiers sur un serveur php, j'en ai créé une à partir de fonctions glanées sur le net.

Contenu du fichier upload/uploader.php (placer ce fichier sur le serveur)

<?php
// Scan de files list
foreach ($_FILES as $key => $value)
{
   // Get the target filename
   $target_path = $HTTP_POST_VARS["target_path"].'/'.$value['name'];

   // Write target filename
   if(copy($value['tmp_name'],$target_path)) 
   {
      echo "OK";
   } 
   else
   {
      echo "KO";
   }
}
?>

Contenu du fichier upload/index.html (placer ce fichier sur le serveur)

<html>
   <body>
      <form enctype="multipart/form-data" action="uploader.php" method="POST">
         <input name="target_path" type="hidden" value="." />
         <label>Choisir fichier : </label>
         <input name="uploader" type="file" /><br />
         <input type="submit" value="Valider" />
      </form>
   </body>
</html>

Pour avoir un accés par mot de passe, ajoutez le fichier suivant upload/.htaccess (lire la notice d'apache pour configurer correctement les mots de passes) (placer ce fichier sur le serveur)

AuthUserFile /var/www/.htpasswd
AuthGroupFile /dev/null
AuthName "ByPassword"
AuthType Basic
require user UserName

Fichier File:HTTPFileUploader.py Classe python pour uploader les fichiers sur le serveur (placer ce fichier sur le poste client)

   1 class HTTPFileUploader:
   2    """ HTTP file uploader """
   3    def __init__(self, host, port=80):
   4       """ Constructor """
   5       from httplib import HTTP
   6       self.host = host
   7       self.port = port
   8       self.user = None
   9       self.password = None
  10       self.page = "upload/uploader.php"
  11       self.fields = {}
  12       self.setTargetPath('.')
  13       self.http = HTTP(self.host, self.port)
  14       
  15    def setLogin(self, user, password):
  16       """ Set user and password """
  17       self.user = user
  18       self.password = password
  19       
  20    def setPage(self, selector = 'upload/uploader.php'):
  21       """ Select the upload page """
  22       self.page = selector
  23       
  24    def setField(self, name, value):
  25       """ Add fields in http """
  26       self.fields[name] = value
  27       
  28    def setTargetPath(self, path):
  29       """ Change the target path """
  30       self.fields["target_path"] = path
  31    
  32    def uploadFile(self, sourceFilename):
  33       """ Upload file on http server """
  34       from string import replace
  35       from base64 import encodestring
  36       
  37       files = (("uploader",sourceFilename,open(sourceFilename,"rb").read()),)
  38       content_type, body = self.encode_multipart_formdata(self.fields, files)
  39       self.http.putrequest('POST', self.page)
  40       if self.user != None and self.password != None:
  41          self.http.putheader("AUTHORIZATION", "Basic %s" % replace(
  42            encodestring("%s:%s" % (self.user, self.password)),
  43            "\012", ""))
  44       self.http.putheader('Content-Type', content_type)
  45       self.http.putheader('Content-Length', str(len(body)))
  46       self.http.endheaders()
  47       self.http.send(body)
  48       errcode, errmsg, headers = self.http.getreply()
  49       result = self.http.file.read()
  50       if result.strip() == "OK":
  51          return True
  52       else:
  53          return False
  54 
  55 
  56    def encode_multipart_formdata(self, fields, files):
  57       """
  58       fields is a sequence of (name, value) elements for regular form fields.
  59       files is a sequence of (name, filename, value) elements for data to be uploaded as files
  60       Return (content_type, body) ready for httplib.HTTP instance
  61       """
  62       BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
  63       CRLF = '\r\n'
  64       L = []
  65       for key, value in fields.items():
  66          L.append('--' + BOUNDARY)
  67          L.append('Content-Disposition: form-data; name="%s"' % key)
  68          L.append('')
  69          L.append(value)
  70       for file in files:
  71          key = file[0]
  72          filename = file[1]
  73          if len(file) > 2:
  74             value = file[2]
  75          else:
  76             value = None
  77          L.append('--' + BOUNDARY)
  78          L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
  79          L.append('Content-Type: %s' % self.get_content_type(filename))
  80          L.append('Content-Transfer-Encoding: binary')
  81          if value:
  82             L.append('')
  83             L.append(value)
  84          else:
  85             L.append('')
  86             fp = open(filename, 'rb')
  87             L.append(fp.read())
  88             fp.close()
  89       L.append('--' + BOUNDARY + '--')
  90       L.append('')
  91       body = CRLF.join(L)
  92       content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  93       return content_type, body
  94 
  95    def get_content_type(self, filename):
  96       import mimetypes
  97       return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  98 
  99 
 100 class HTTPSFileUploader(HTTPFileUploader):
 101    """ HTTPS file uploader """
 102    def __init__(self, host, port=443):
 103       """ Constructor """
 104       from httplib import HTTPS
 105       HTTPFileUploader.__init__(self, host, port)
 106       self.http = HTTPS(self.host, self.port)

***IMPORTANT***

si votre serveur web utilise des "virtual host" et que vous specifiez "www.example.com" comme Hostname, vous devez absolument mettre le URL complet comme ceci uploader.setPage('http://www.example.com/upload/uploader.php') sinon votre serveur web cherchera dans le document root de votre "default virtual host" et ne trouvera pas votre script d'upload.

Exemple pour un serveur http sans accés par mot de passe

   1 from HTTPFileUploader import *
   2 if __name__ == '__main__':
   3    uploader = HTTPFileUploader("192.168.1.156") # Hostname du serveur
   4    uploader.setPage('/upload/uploader.php') # Choix de la page d'upload
   5    print uploader.uploadFile('d://toto.txt')

Exemple pour un serveur https avec accés par mot de passe

   1 from HTTPFileUploader import *
   2 if __name__ == '__main__':
   3    uploader = HTTPSFileUploader("192.168.1.156") 
   4    uploader.setPage('/upload/uploader.php')
   5    uploader.setLogin('user','password') # Insert your login password
   6    #uploader.setTargetPath('titi') <- Pour configurer un chemin de destination des fichiers sur le serveur
   7    print uploader.uploadFile('d://toto.txt')

Exemple pour uploader plusieurs fichiers d'un seul coup

   1 from HTTPFileUploader import *
   2 if __name__ == '__main__':
   3    uploader = HTTPSFileUploader("192.168.1.156") 
   4    uploader.setPage('/upload/uploader.php')
   5    from glob import glob
   6    for file in glob("*.*"):
   7       print file,uploader.uploadFile(file)

2016-06-05 21:42