submitting a jpeg to a web site?

John J. Lee jjl at pobox.com
Mon Nov 10 19:55:47 EST 2003


"Georgy Pruss" <SEE_AT_THE_END at hotmail.com> writes:

> "Steven D.Arnold" <stevena at neosynapse.net> wrote in message news:mailman.594.1068457889.702.python-list at python.org...
> | Hi,
> |
> | I am curious how one might submit a JPEG to a web site using Python.
> | I've tried urllib.urlopen, passing a dictionary that contained a key
> | pointing to a string that contains the bytes of the JPEG, but that
> | didn't apparently work.

No -- you need to give urllib (or urllib2, better) the raw data to be
posted, which should be MIME multipart/form-data encoded (which
involves adding those funny lines starting with '--').  You also need
appropriate HTTP headers.


> | I did use the urllib.urlencode function on the
> | dict before calling urlopen.  It seems on the face of it that urlopen
> | is not the ordained way to do what I want here.

URL encoding is for the other way of uploading form data
(application/x-www-form-urlencoded -- no peculiar MIME encoding in
that case, just foo=bar&spam=eggs).  multipart/form-data was invented
because it would be clunky to try to shoehorn both ordinary form
control data and large uploaded, possibly binary, files into the
URL-encoded format.


> | The <form> tag of the page I'm submitting to looks like this:
> |
> | <form action="application_one_process.php" name="mainForm"
> | method="POST" enctype="multipart/form-data" accept-charset="US-ASCII">

1. web-sig mailing list archives has a few functions for generating
   the appropriate data to pass to urlopen.  You then just have to
   have the appropriate HTTP headers (I forget, but I think just
   Content-Type).

2. ClientForm (assuming you don't mind urlopening the web page with
   the form each time you want to submit it -- alternatively, keep the
   web page or just the form in a string or local file and use
   ClientForm.ParseFile, or pickle the HTMLForm objects, or whatever):

http://wwwsearch.sf.net/ClientForm/

r = urllib2.urlopen("http://www.example.com/form.html")
forms = ClientForm.ParseResponse(r)
r.close()
form = forms[0]

f = open("data.dat")
form.add_file(f, "text/plain", "data.dat")
request = form.click()
r2 = urllib2.urlopen(request)
f.close()
print r2.read()
r2.close()


[...]
> It's not a "product version", but it works at my site (Windows XP,
[...]
> print "Content type: text/html"
> print
[...]


Georgy, Steve was asking about about the client side.  An easy mistake
to make, I know...


John




More information about the Python-list mailing list