1. Use the URLLIB2 primitive way
Import urllib2__author__ = ' Huangjianan ' def post_file (url,filepath,header): boundary = ' Iyhwit-ambwsbs32ckrylccv4lp-3n ' #body pic_type=filepath.split ('. ') [-1] data = [] data.append ('--%s '% boundary) Fr=open (filepath, ' RB ') data.append (' content-disposition: Form-data; Name= "%s"; Filename= "test.%s" '% (' avatafile ', Pic_type)) data.append (' content-type:image/%s\r\n '% pic_type) buffer= Fr.read () data.append (buffer) fr.close () data.append ('--%s--\r\n '% boundary) http_body= ' \ r \ n '. Join (data) req=urllib2. Request (URL, data=http_body) #header for (k,v) in Header.items (): req.add_header (k,v) resp = Urllib2.urlopen (req, timeout=5) response=resp.read () return response
2. Using the Requests method
Import requestsheaders = {' Content-type ': ' application/x-www-form-urlencoded; Charset=utf-8 ', ' accept-encoding ' : ' gzip,deflate '}fileparams = {"Filedata": (Filepath.split ("/") [-1], open (Abspath, "RB"), "Application/octet-stream") }r = Requests.post (URL, data={},files=fileparams, headers=headers)
Python post upload file