开发者

how do I base encode a binary file (JPG) in ruby

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 Po开发者_如何学运维stalcard using paperclip)

Thanks.


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜