Content-Type in for individual files in python requests
Question:
I want to request to my server running in python flask with file and some meta information. Hence my request content-Type will be ‘multipart/form-data. Is there a way i can set the content type of file like image/jpg, image/gif etc…
How do i set the content-type for the file. Is it possible or not
Answers:
If you make each file specification a tuple, you can specify the mime type as a third parameter:
files = {
'file1': ('foo.gif', open('foo.gif', 'rb'), 'image/gif'),
'file2': ('bar.png', open('bar.png', 'rb'), 'image/png'),
}
response = requests.post(url, files=files)
You can give a 4th parameter as well, which must be a dictionary with additional headers for each part.
See the Requests API documentation:
file-tuple
can be a 2-tuple ('filename', fileobj)
, 3-tuple ('filename', fileobj, 'content_type')
or a 4-tuple ('filename', fileobj, 'content_type', custom_headers)
, where 'content-type'
is a string defining the content type of the given file and custom_headers
a dict-like object containing additional headers to add for the file.
import requests
url = "http://png_upload_example/upload"
# files = [(<key>, (<filename>, open(<file location>, 'rb'), <content type>))]
files = [('upload', ('thumbnail.png', open('thumbnail.png', 'rb'), 'image/png'))]
response = requests.request("POST", url, files = files)
I want to request to my server running in python flask with file and some meta information. Hence my request content-Type will be ‘multipart/form-data. Is there a way i can set the content type of file like image/jpg, image/gif etc…
How do i set the content-type for the file. Is it possible or not
If you make each file specification a tuple, you can specify the mime type as a third parameter:
files = {
'file1': ('foo.gif', open('foo.gif', 'rb'), 'image/gif'),
'file2': ('bar.png', open('bar.png', 'rb'), 'image/png'),
}
response = requests.post(url, files=files)
You can give a 4th parameter as well, which must be a dictionary with additional headers for each part.
See the Requests API documentation:
file-tuple
can be a 2-tuple('filename', fileobj)
, 3-tuple('filename', fileobj, 'content_type')
or a 4-tuple('filename', fileobj, 'content_type', custom_headers)
, where'content-type'
is a string defining the content type of the given file andcustom_headers
a dict-like object containing additional headers to add for the file.
import requests
url = "http://png_upload_example/upload"
# files = [(<key>, (<filename>, open(<file location>, 'rb'), <content type>))]
files = [('upload', ('thumbnail.png', open('thumbnail.png', 'rb'), 'image/png'))]
response = requests.request("POST", url, files = files)