2 Replies - 6430 Views - Last Post: 28 November 2010 - 12:44 PM Rate Topic: -----

#1 aonbyte  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 26
  • Joined: 08-October 10

Problems with uploading an image (urllib2 requests)

Posted 27 November 2010 - 07:51 PM

I tried googling and reading the urllib2 documentation. However I am stuck at the moment. I am trying to upload an image to a website(http://imgur.com). When I try to open the url with a certain request I get this error "HTTP Error 400: Bad Request"

This is the API documentation for imgur that I reffered to for uploading requests: http://api.imgur.com...ces_anon#upload

This is the code I've been working on (Also the code that doesn't work)

#apikey is 02b62fd8f1d5e78321e62bb42ced459e
#url for uploading is  http://api.imgur.com/2/upload 
#image file in the directory is pic.png

import urllib
import urllib2

picture = open('pic.png')
url = 'http://api.imgur.com/2/upload'
parameters = {'key' : '02b62fd8f1d5e78321e62bb42ced459e', 'image' : picture}
data = urllib.urlencode(parameters)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)



I tried figuring out what the problem may be. Reading the documentation on imgur I found that the image parameter must be "A binary file, base64 data, or a URL." I tried using a url for the parameter and it worked perfectly.

i.e.
This code works but I need to be able to use an actual image file on my computer instead of a url to upload an image
#apikey is 02b62fd8f1d5e78321e62bb42ced459e
#url for uploading is  http://api.imgur.com/2/upload 
#image file in the directory is pic.png

import urllib
import urllib2

picture = 'http://www.opticianonline.net/blogs/big-optometry-blog/eiffel-tower-picture.jpg'
url = 'http://api.imgur.com/2/upload'
parameters = {'key' : '02b62fd8f1d5e78321e62bb42ced459e', 'image' : picture}
data = urllib.urlencode(parameters)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)



So I figured that my problem is with the image parameter. I can't seem to pass an open file in python as the parameter. What can I do?

Is This A Good Question/Topic? 0
  • +

Replies To: Problems with uploading an image (urllib2 requests)

#2 aonbyte  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 26
  • Joined: 08-October 10

Re: Problems with uploading an image (urllib2 requests)

Posted 27 November 2010 - 08:35 PM

I figured it out by encoding the image file into a base64 string and passing that as my image parameter. It worked. Thanks anyways for the help.
Was This Post Helpful? 1
  • +
  • -

#3 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6053
  • View blog
  • Posts: 23,488
  • Joined: 23-August 08

Re: Problems with uploading an image (urllib2 requests)

Posted 28 November 2010 - 12:44 PM

Glad you got it sorted out. Thanks for coming back and providing the solution!
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1