I had such good success with the question about the HTML canvas element and drawImage, I thought it might be a good idea to bring my next vexing problem to the Scripting News brain trust. Maybe you guys can help me get over this hump as well. (I've already dumped all the details on Dan MacTough, so I'm in a good place for asking the question more broadly.)
Basically, I want to send a tweet with an attached image.
I have the PNG in memory on the client side, the result of calling canvas.toDataURL ().
The result is good. I've tried writing it to disk and it shows correctly in a browser.
I can send it up to the server as the body of a POST. What shows up there is a correct PNG image with a little bit of info at the front, data:image/png;base64
, indicating that it's a PNG and it's base64 encoded. If I delete the prefix and write the file to disk it's a good PNG file.
A caveat, I have written lots of code that uses the Node.js request package, successfully, but this is the first time I've used it to create a multipart form, as required by the Twitter API routine. I'm pretty sure that's why I'm getting hung up.
Another caveat, I use the node-twitter-api package to interface to the Twitter API. It's been an enormous help. But the comment at the bottom of the docs page about update_with_media is cryptic. I have tried using it to do this job, but it doesn't work. When I looked at the code, I found it was virtually identical to the other examples I was looking at.
Here's a gist containing the code that's running on the server.
body is the body of the POST message described in the first section.
This is the post I'm modeling my code after.
If you look at the CoffeeScript example he cites, they're doing some really fancy shit I don't understand to create a stream.
form.append('media[]', fs.createReadStream(path.normalize(file_path)))
That's the magic incantation I'm trying to recreate (assuming this code works, I have no proof that it actually does).
Problem is I don't have a file path.
I have the result of calling canvas.toDataURL (). Here's the code from the client that's calling this bit of server code.
I have a buffer. It seems the call to form.append ("media[]" needs a parameter that's of a different type. Not sure what that type is, or how to create it. I don't want to write a file, because I have the whole PNG in memory. It seems ridiculous to write a file. Regardless, I've tried that (I'm desperate) and it didn't work.
BTW, here's a screen shot of the error I get when I run this code, any variant of it, on Heroku in Node.
I'm in over my head. I've tried reading the code of request and the form-data package.
I just want to send an image to Twitter.
The code now works.
In this comment I explain the three problems.
Here's a gist containing the correct code.