Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quickly encode a file in ruby to base64
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/,"")
@pvin

This comment has been minimized.

Copy link

@pvin pvin commented Dec 22, 2017

Hi @bkenny thanks for the Base64.encoding script.
a. How I do Base64.decoding? meaning again the mp4 video from encoded string.

@pvin

This comment has been minimized.

Copy link

@pvin pvin commented Dec 22, 2017

Sorry got it.
File.open("/home/folder_name/file_name.mp4", "wb") do |file|
file.write(Base64.decode64(encoded))
end

@mcansky

This comment has been minimized.

Copy link

@mcansky mcansky commented Mar 3, 2020

thanks

@calmerwaters

This comment has been minimized.

Copy link

@calmerwaters calmerwaters commented Jun 4, 2020

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 ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment