I would like to send a file in a POST
request using Python's Requests library, in Python 3. I'm trying to send it like so:
import requests
file_content = 'This is the text of the file to upload'
r = requests.post('http://endpoint',
params = {
'token': 'api_token',
'message': 'message text',
},
files = {'filename': file_content},
)
The server responds that no files were sent, however. Should this work? Most examples involve passing a file object, but I don't want to have to write the string out to disk just to upload it.
Method 1: Using the Python's os Module: Also, the enctype attribute with "multi-part/form-data" value will help the HTML form to upload a file. Lastly, we need the input tag with the filename attribute to upload the file we want. Lastly, we need the input tag with the filename attribute to upload the file we want.
When writing responses to file you need to use the open function with the appropriate file write mode. For text responses you need to use "w" - plain write mode. For binary responses you need to use "wb" - binary write mode.
We can use the write() method to put the contents of a string into a file or use writelines() if we have a sequence of text to put into the file. For CSV and JSON data, we can use special functions that Python provides to write data to a file once the file is open.
The requests
docs provide us with this:
If you want, you can send strings to be received as files:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}
I posted it as another answer as it involves a different approach.
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