views:

1168

answers:

2

I'm trying to upload an image to PingFM. Their documentation says:

media – base64 encoded media data.

I can access this image via the URL. I tried (practically guessed) this:

ActiveSupport::Base64.encode64(open("http://image.com/img.jpg"))

But I get this error:

TypeError: can't convert Tempfile into String from /usr/lib/ruby/1.8/base64.rb:97:in pack' from /usr/lib/ruby/1.8/base64.rb:97:in encode64' from (irb):19 from :0

What do I do? Thank you!

+3  A: 

Encode a file to base64 encoding:

File.open("output_file","w"){|file| file.write [open("link_to_file").string].pack("m")}

Decode base64 encoded file:

File.open('original', 'wb') {|file| file << (IO.readlines('output_file').to_s.unpack('m')).first }
khelll
+2  A: 

The open method:

open("http://image.com/img.jpg")

is returning a Tempfile object, while encode64 expects a String.

Calling read on the tempfile should do the trick:

ActiveSupport::Base64.encode64(open("http://image.com/img.jpg") { |io| io.read })
mtyaka
Or .string should work as well.
khelll
manveru
@manveru Right. Thanks for the comment - I updated the answer.
mtyaka