1

first excuse me for my bad english (i speak spanish).

I am trying submit a form uploading with an image.

When i want send normal data (how text string) i do this:

First import modules:

import urllib.request

import urllib.parse

import http.cookiejar

Preparing cookies and headers:

cj = http.cookiejar.CookieJar()
open = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
abriendo.addheaders = [("User-agent","Mozilla/5.0")]
urllib.request.install_opener(open)

Encode the url data, i use the id (it is in the web form html )

valor1 = {"username":"test1","password","hello"}
valor2 = urllib.parse.urlencode(valor1)
finalvalor = valor2.encode("UTF-8")

Now can send post data (remember, this is an example with string data)

nav = urllib.request.urlopen(url,finalvalor)
navread = str(nav.read())

Url variable have the post url

This work good, but i have problems to send a image.

The web form start with this code:

 <form enctype="multipart/form-data" onsubmit="return ver('espera');"
          action="example.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="5300000">
            <br><br>
            <div align="center" id="uploadFileContainer">
                <input size="25" id="uploadFile1" name="uploadFile1" type="file">

I do

dicc = {"uploadFile1":open("1.jpg","rb")}
nav = urllib.request.urlopen(url,dicc)
navread = str(nav.read())

Have this Error:

ValueError: Content-Length should be specified for iterable data of type <class 'dict'> {'uploadFile1': <_io.BufferedReader name='1.jpg'>

I try to encode the data ( enconde dicc how normal url ) but not work (do not send any data). I surfed in googe and i think that binary data need to encode to base64 ??

Finally, the question is, how can upload a image with urllib.request module?

Thanks for read.

erni
  • 176
  • 1
  • 1
  • 10

1 Answers1

1

The simple way to send a file in python, is to use the requests library:

import requests
files = {'file': open('1.jpg', 'rb')}
r = requests.post(url, files=files)
print(r.text)

cf requests' documentation. It basically does all what you try to do, but makes it easy and very pythonic.

zmo
  • 24,463
  • 4
  • 54
  • 90