I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field.
Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it.
Net::HTTP doesn't look like the best idea. curb is looking good.
there's also nick sieger's multipart-post to add to the long list of possible solutions.
Well the solution with NetHttp has a drawback that is when posting big files it loads the whole file into memory first.
After playing a bit with it I came up with the following solution:
curb
looks like a great solution, but in case it doesn't meet your needs, you can do it withNet::HTTP
. A multipart form post is just a carefully-formatted string with some extra headers. It seems like every Ruby programmer who needs to do multipart posts ends up writing their own little library for it, which makes me wonder why this functionality isn't built-in. Maybe it is... Anyway, for your reading pleasure, I'll go ahead and give my solution here. This code is based off of examples I found on a couple of blogs, but I regret that I can't find the links anymore. So I guess I just have to take all the credit for myself...The module I wrote for this contains one public class, for generating the form data and headers out of a hash of
String
andFile
objects. So for example, if you wanted to post a form with a string parameter named "title" and a file parameter named "document", you would do the following:Then you just do a normal
POST
withNet::HTTP
:Or however else you want to do the
POST
. The point is thatMultipart
returns the data and headers that you need to send. And that's it! Simple, right? Here's the code for the Multipart module (you need themime-types
gem):I had the same problem (need to post to jboss web server). Curb works fine for me, except that it caused ruby to crash (ruby 1.8.7 on ubuntu 8.10) when I use session variables in the code.
I dig into the rest-client docs, could not find indication of multipart support. I tried the rest-client examples above but jboss said the http post is not multipart.
The multipart-post gem works pretty well with Rails 4 Net::HTTP, no other special gem
https://github.com/Feuda/multipart-post/tree/patch-1
I can't say enough good things about Nick Sieger's multipart-post library.
It adds support for multipart posting directly to Net::HTTP, removing your need to manually worry about boundaries or big libraries that may have different goals than your own.
Here is a little example on how to use it from the README:
You can check out the library here: http://github.com/nicksieger/multipart-post
or install it with:
If you're connecting via SSL you need to start the connection like this: