Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode media in base64 given URL in Ruby

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 
like image 319
Ramon Tayag Avatar asked Oct 10 '09 03:10

Ramon Tayag


People also ask

Can you use Base64 in URL?

Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs.

Is URL encoding the same as Base64?

The URL encoding is the same as Basic encoding the only difference is that it encodes or decodes the URL and Filename safe Base64 alphabet and does not add any line separation. String encodedURL = Base64.


1 Answers

To encode a file:

require 'base64' Base64.encode64(File.open("file_path", "rb").read) 

To produce the file from the encoded string:

require 'base64' encoded_string = Base64.encode64(File.open("file_path", "rb").read)  File.open(file_name_to_create, "wb") do |file|     file.write(Base64.decode64(encoded_string)) end 
like image 116
Marielyn Alvarado Avatar answered Sep 28 '22 23:09

Marielyn Alvarado