[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Encoding a multipart/form-data for posting via HTTP

Dema

3/10/2005 7:15:00 AM

After googling around (with no luck) for a while for a function that
would encode a hash into a multipart/form-data to be sent to a HTTP
server via POST, I decided to read the RFC and write my own. In fact,
it's not that complicated and I would like to share it just in case
someone else needs it:

BOUNDARY = "AaB03x"
def encode_multipartformdata(parameters = {})
ret = String.new
parameters.each do |key, value|
unless value.empty?
ret << "\r\n--" << BOUNDARY << "\r\n"
ret << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
ret << value
end
end
ret << "\r\n--" << BOUNDARY << "--\r\n"
end

I got stuck for a while on the boundary syntax and the \r\n stuff, but
eventually it worked ok.

I just needed it to send some data to a RDF database that offers a HTTP
API channel. So, this only works for the simplest case. There are some
more complex variations, like uploading one or more files, setting
individual content types for each part, etc.

rgds
Dema

2 Answers

Dave Burt

3/10/2005 8:47:00 AM

0

It sounds to me as if this should be in Net::HTTP::Post.

"Dema" <demetriusnunes@gmail.com> offered:
> After googling around (with no luck) for a while for a function that
> would encode a hash into a multipart/form-data to be sent to a HTTP
> server via POST, I decided to read the RFC and write my own. In fact,
> it's not that complicated and I would like to share it just in case
> someone else needs it:
>
> BOUNDARY = "AaB03x"
> def encode_multipartformdata(parameters = {})
> ret = String.new
> parameters.each do |key, value|
> unless value.empty?
> ret << "\r\n--" << BOUNDARY << "\r\n"
> ret << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
> ret << value
> end
> end
> ret << "\r\n--" << BOUNDARY << "--\r\n"
> end
>
> I got stuck for a while on the boundary syntax and the \r\n stuff, but
> eventually it worked ok.
>
> I just needed it to send some data to a RDF database that offers a HTTP
> API channel. So, this only works for the simplest case. There are some
> more complex variations, like uploading one or more files, setting
> individual content types for each part, etc.
>
> rgds
> Dema
>


Dema

3/10/2005 6:24:00 PM

0


Dave Burt wrote:
> It sounds to me as if this should be in Net::HTTP::Post.
>
I agree completely.