This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.
The post() method sends a POST request to the specified url. The post() method is used when you want to send some data to the server.
import requests dfile = open("datafile. txt", "rb") url = "http://httpbin.org/post" test_res = requests. post(url, files = {"form_field_name": dfile}) if test_res. ok: print(" File uploaded successfully !
Best thing I can think of is to encode it yourself. How about this subroutine?
from urllib2 import Request, urlopen
from binascii import b2a_base64
def b64open(url, postdata):
req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
return urlopen(req)
conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité")
# returns a file-like object
(Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With