Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 REST based invocation. The Python script should invoke a REST URL and submit the file when the script is called.

This is similar to multipart POST that is done by browser when uploading a file; but here I want to do it through Python script.

If possible do not want to add any external libraries to Python and would like to keep it fairly simple python script using the core Python install.

Can some one guide me? or share some script example that achieve what I want?

like image 747
AniJ Avatar asked Nov 09 '11 07:11

AniJ


People also ask

How do I upload a file to multipart form?

Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.

How do I upload a file to a Python URL?

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 !


2 Answers

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)
like image 161
Jesvin Jose Avatar answered Oct 05 '22 20:10

Jesvin Jose


A RESTful way to upload an image would be to use PUT request if you know what the image url is:

#!/usr/bin/env python3
import 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 python3
import requests

response = requests.post('http://httpbin.org/post',
                         files={'file': open('filename','rb')})
print(response.content)
like image 25
jfs Avatar answered Oct 05 '22 20:10

jfs