Home » Python » Python HTTP file transfer based on examples

Python HTTP file transfer based on examples

this article mainly introduces the Python realization method based on HTTP file transfer, with examples in detail about the implementation of the code of server terminal and client, very practical, a friend in need can refer to the

examples about the method of Python system based on HTTP file transfer. Share to you for your reference. Specific implementation methods are as follows:

: a problem, because of the need to look at recent requests via POST to transfer files and write Server and Client to achieve a simple opportunity HTTP file transfer tool

two, code:


From BaseHTTPServer import BaseHTTPRequestHandler
Import CGI
Class PostHandler (BaseHTTPRequestHandler):
Def do_POST (self):
Form = cgi.FieldStorage
'CONTENT_TYPE': self.headers['Content-Type'],
Self.send_response (200)
Self.end_headers ()
Self.wfile.write ('Client:%sn '% str (self.client_address))
Self.wfile.write ('User-agent:,%sn',%, str (self.headers['user-agent']))
Self.wfile.write ('Path:,%sn'%self.path)
Self.wfile.write ('Form, data:n')
For, field, in, form.keys ():
Field_item = form[field]
Filename = field_item.filename
Filevalue = field_item.value
Filesize = len (filevalue) # file size (bytes)
Print len (filevalue)
With, open (filename.decode ('utf-8'), +'a','wb') as f:
F.write (filevalue)
If __name__=='__main__':
From BaseHTTPServer import HTTPServer
Sever = HTTPServer (('localhost', 8080), PostHandler)
Print,'Starting, server, use, , to, stop'
Sever.serve_forever ()
Client end:

Import requests
Url ='http://localhost:8080'
Path = u'D: fast disk Ali Avatar.Jpg'
Print path
Files = {'file': open (path,'rb')}
R = requests.post (URL, files=files)
Print, r.url, r.text