Created
August 21, 2013 12:58
-
-
Save bkenny/6294133 to your computer and use it in GitHub Desktop.
Quickly encode a file in ruby to base64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'base64' | |
# Open the file you wish to encode | |
data = File.open('/Users/bkenny/Desktop/d3cce16ee41411e296c022000a1f980f_101.mp4').read | |
# Encode the puppy | |
encoded = Base64.encode64(data) | |
# Spit it out into one continous string | |
puts encoded.gsub(/\n/,"") |
thanks
You could just use the following, to save the last step:
require 'base64'
# Open the file you wish to encode
data = File.open('/Users/bkenny/Desktop/d3cce16ee41411e296c022000a1f980f_101.mp4').read
# Encode the puppy
encoded = Base64.strict_encode64(data)
See reference for strict_encode64
https://ruby-doc.org/stdlib-2.4.1/libdoc/base64/rdoc/Base64.html#method-i-strict_encode64
Note: this means no new lines are added ;)
For anyone else that comes across that was struggling like me, I've found I have to use .binread
instead of .read
to correctly encode an uploaded image file (or more specifically, the tempfile that rails creates in that situation), otherwise the base64 encoding data comes out woefully short and you'll get invalid results trying to decode or send to an external API (such as Google Cloud Vision).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry got it.
File.open("/home/folder_name/file_name.mp4", "wb") do |file|
file.write(Base64.decode64(encoded))
end