Python implements an HTTP-based file transfer instance,

Source: Internet
Author: User

Python implements an HTTP-based file transfer instance,

This example describes how to implement HTTP-based file transfer in Python. Share it with you for your reference. The specific implementation method is as follows:

I. Problems:

Because I recently read the content of the file transmitted through the POST request and wrote the Server and Client to implement a simple HTTP File Transfer tool.

II. Implementation Code:

Server:
Copy codeThe 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) # file size (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 <Ctrl-C> to stop'
Sever. serve_forever ()
Client:
Copy codeThe Code is as follows: # coding = UTF-8
Import requests
Url = 'HTTP: // localhost: 8080'
Path = u 'd: .jpg'
Print path
Files = {'file': open (path, 'rb ')}
R = requests. post (url, files = files)
Print r. url, r. text

I hope 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.