Python urllib2 file upload problems

烂漫一生 提交于 2019-11-30 05:23:57

If you're using Python 2.5 or newer, urllib2_file is both unnecessary and unsupported, so check which version you're using (and perhaps upgrade).

If you're using Python 2.3 or 2.4 (the only versions supported by urllib2_file), try running the sample code and see if you have the same problem. If so, there is likely something wrong either with your Python or urllib2_file installation.

EDIT:

Also, you don't seem to be using either of urllib2_file's two supported formats for POST data. Try using one of the following two lines instead:

d = ['uploaded', open(sys.argv[1:])]
## --OR-- ##
d = {'uploaded': open(sys.argv[1:])}

First, there's a third way to run Python programs.

From cmd.exe, type python myprogram.py. You get a nice log. You don't have to type stuff one line at a time.

Second, check the urrlib2 documentation. You'll need to look at urllib, also.

A Request requires a URL and a urlencoded encoded buffer of data.

data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format.

You need to encode your data.

If you're still on Python2.5, what worked for me was to download the code here:

http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html

and save it as MultipartPostHandler.py

then use:

import urllib2, MultipartPostHandler

opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler())
opener.open(url, {"file":open(...)})

or if you need cookies:

import urllib2, MultipartPostHandler, cookielib

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MultipartPostHandler.MultipartPostHandler())
opener.open(url, {"file":open(...)})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!