3

I already have binary data read from a file. Most of the examples I see online link directly to the file, and upload the whole file. I am looking how to upload the binary data that I already have from another source via HTTP POST in python.

esac
  • 23,283
  • 37
  • 120
  • 174

2 Answers2

6

Alternatively:

req = urllib2.Request("http://example.com", data, {'Content-Type': 'application/octet-stream'})
urllib2.urlopen(req)

That also shows how you can specify the Content-Type of the data.

Matthew Flaschen
  • 268,153
  • 48
  • 509
  • 534
0

I'm not sure what online examples you're looking at, but urllib2.urlopen takes the data to post as a chunk of data and not a file at all.

Greg Hewgill
  • 890,778
  • 177
  • 1,125
  • 1,260
  • Example: http://www.2maomao.com/blog/python-http-post-a-binary-file-using-urllib2/ – esac Oct 23 '11 at 06:59
  • I'll have to take a network sniff. The server that I am POST'ing to is issuing a 400 Bad Request when I try that. – esac Oct 23 '11 at 07:00
  • 1
    Okay, so that example reads the data from a file into `png_data`. If you already have the data in memory, just use that in the calls to `urllib2`. – Greg Hewgill Oct 23 '11 at 07:01