Python 3 Script To Upload A File To A Rest Url (multipart Request)
I am fairly new to Python and using Python 3.2. I am trying to write a python script that will pick a file from user machine (such as an image file) and submit it to a server using
Solution 1:
Requests library is what you need. You can install with pip install requests
.
http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file
>>>url = 'http://httpbin.org/post'>>>files = {'file': open('report.xls', 'rb')}>>>r = requests.post(url, files=files)
Solution 2:
A RESTful way to upload an image would be to use PUT
request if you know what the image url is:
#!/usr/bin/env python3import http.client
h = http.client.HTTPConnection('example.com')
h.request('PUT', '/file/pic.jpg', open('pic.jpg', 'rb'))
print(h.getresponse().read())
upload_docs.py contains an example how to upload a file as multipart/form-data
with basic http authentication. It supports both Python 2.x and Python 3.
You could use also requests
to post files as a multipart/form-data
:
#!/usr/bin/env python3import requests
response = requests.post('http://httpbin.org/post',
files={'file': open('filename','rb')})
print(response.content)
Solution 3:
You can also use unirest . Sample code
import unirest
# consume async post requestdefconsumePOSTRequestSync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method# actually unirest does not provide variable to shift between# application-x-www-form-urlencoded and# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = unirest.post(url, headers = headers,params = params)
print"code:"+ str(response.code)
print"******************"print"headers:"+ str(response.headers)
print"******************"print"body:"+ str(response.body)
print"******************"print"raw_body:"+ str(response.raw_body)
# post sync request multipart/form-data
consumePOSTRequestSync()
You can check out this post http://stackandqueue.com/?p=57 for more details
Post a Comment for "Python 3 Script To Upload A File To A Rest Url (multipart Request)"