views:

120

answers:

1

I have a binary files which needs to be sent as a string to a third-party web-service. Turns out it requires that it needs to be base64 encoded.

In ruby I use the following:

      body = body << Base64.b64encode(IO.read("#{@postalcard.postalimage.path}"))

body is a strong which conists of a bunch of strings as parameters.

Does this look right? (the file is loaded into the model Postalcard using paperclip)

Thanks.

+2  A: 

Base64.b64encode prints out the base 64 encoded version of 60 char length by default. For example, if I will do

Base64.b64encode('StackOverflow')
#=> prints U3RhY2tPdmVyZmxvdw==
#=> returns "U3RhY2tPdmVyZmxvdw==\n"

If I give it a length, lets say 4

Base64.b64encode('StackOverflow', 4)
#=> prints U3Rh
#=> prints Y2tP
#=> prints dmVy
#=> prints Zmxv
#=> prints dw==
#=> returns "U3RhY2tPdmVyZmxvdw==\n"

But if you dont want to print out the encoded string to stdout and only return its value, which I think what you need, then use

Base64::encode64('StackOverflow')
#=> "U3RhY2tPdmVyZmxvdw==\n"
nas
oh I see, so in other words, .b64encode truncates it to 60?
Angela
No it doesn't truncates the passed string. In addition to, returning the encoded string it also prints outs the encoded version in lines of 60 characters by default else it will print out the characters equal to the second argument as I gave in my example above i.e. `Base64.b64encode('StackOverflow', 4)`
nas
okay so for my purposes, I should use base64.encode64? I want to pass the encoded string as part of a string into a web service....
Angela
No `Base64::encode64` should be fine because it does returns the encoded string but it just doesnt prints it out to `stdout` as shown in my answer above.
nas