Python implementation-based HTTP file transfer instance

Source: Internet
Author: User
The examples in this article describe how Python implements HTTP file-based transfer. Share to everyone for your reference. The implementation method is as follows:

First, the question:

Because I need to look at it recently. Transferring the contents of a file via a POST request and writing it yourself server and client implement a simple Opportunity HTTP file Transfer tool

Second, the implementation of code:

Server side:

The code is as follows:

#coding =utf-8
From Basehttpserver import Basehttprequesthandler
Import CGI
Class Posthandler (Basehttprequesthandler):
def do_post (self):
form = CGI. Fieldstorage (
Fp=self.rfile,
Headers=self.headers,
environ={' request_method ': ' POST ',
' 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) #文件大小 (bytes)
Print Len (filevalue)
With open (Filename.decode (' utf-8 ') + ' A ', ' WB ') as F:
F.write (Filevalue)
Return
If __name__== ' __main__ ':
From Basehttpserver import Httpserver
Sever = Httpserver ((' localhost ', 8080), Posthandler)
print ' Starting server, use To stop '
Sever.serve_forever ()


Client side:

The code is as follows:

#coding =utf-8
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

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.