0

I'm using jsOauth-twitter to upload an image to twitter which calls the update_with_media api method. It looks like it needs the actual image data. This is already on my webpage inside a normal <img src="localfile"> tag.

Using Javascript, can I get at the actual image data (JPEG) to pass it to the function? Is it available in the DOM? I need the raw image data so I can pass it to twitter as application/octet-stream, so base64 is no good to me.

paulmorriss
  • 2,579
  • 25
  • 30

1 Answers1

1

It looks like the API requires the form to be sent as multipart/form-data, which means the media[] parameter is expecting a file rather than binary or base64 encoded data. If you use HTML file input inside a form, this should be fairly straightward.

If you must use the <img> tag, then it would be difficult. All I can think of is draw the image to a <canvas>, obtain a base64-encoded URI with toDataURI(), decode it to obtain the raw image data using window.atob(), then build the multipart/form-data POST body manually. This answer has some sample code for the first couple of things.

The Blob API may help in creating a file-like object which your OAuth library can accept (rather than manually building the request body), but its not very well supported yet.

Community
  • 1
  • 1
Graham
  • 6,484
  • 2
  • 35
  • 39
  • You might want to check this answer out: http://stackoverflow.com/a/934925/341353 – abitgone Jun 20 '12 at 15:13
  • I don't have to use the image tag, I just thought that might be easy as the browser has already loaded it. Putting the img tag in a form is no problem. How do I refer to the image tag in that case? It's not an input or other form field. – paulmorriss Jun 20 '12 at 15:20
  • Yes that does the first step of obtaining the base64 data, but not decoding or posting it to Twitter which is the OPs objective. – Graham Jun 20 '12 at 15:21
  • @paul If its not loaded via an then you'll have to use the method as described above / by the link from abitgone. – Graham Jun 20 '12 at 15:23
  • I need the file in application/octet-stream (Twitter requirement) not base64. – paulmorriss Jun 29 '12 at 13:07
  • One you have retrieved the base64-encoded data via the canvas `toDataURI()` method, you can then use the `atob()` method https://developer.mozilla.org/en/DOM/window.atob (or use a library) to decode it and access the raw binary data. – Graham Jul 02 '12 at 11:22
  • @Graham I've edited the answer to include that. I could have used a library, but native code should be quicker hopefully. – paulmorriss Jul 03 '12 at 12:41