Skip to content

Instantly share code, notes, and snippets.

@simonqian
Created April 14, 2017 09:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simonqian/490302d44d401e7a27f45d200cb2b493 to your computer and use it in GitHub Desktop.
Save simonqian/490302d44d401e7a27f45d200cb2b493 to your computer and use it in GitHub Desktop.
base64 to file in rails
module Base64ToFile
extend ActiveSupport::Concern
def base64_to_file(base64_data, filename=nil)
return base64_data unless base64_data.is_a? String
start_regex = /data:image\/[a-z]{3,4};base64,/
filename ||= SecureRandom.hex
regex_result = start_regex.match(base64_data)
if base64_data && regex_result
start = regex_result.to_s
tempfile = Tempfile.new(filename)
tempfile.binmode
tempfile.write(Base64.decode64(base64_data[start.length..-1]))
uploaded_file = ActionDispatch::Http::UploadedFile.new(
:tempfile => tempfile,
:filename => "#{filename}.jpg",
:original_filename => "#{filename}.jpg"
)
uploaded_file
else
nil
end
end
end
@lafeber
Copy link

lafeber commented Jan 18, 2021

  def base64_to_file(base64_data)
    return base64_data unless base64_data.is_a? String

    regex = /data:image\/([a-z]{3,4});base64,([a-zA-Z0-9=]*)/
    type, image = base64_data.scan(regex)[0]
    return unless type && image

    filename = "#{SecureRandom.hex}.#{type}"
    tempfile = Tempfile.new(filename)
    tempfile.binmode
    tempfile.write(Base64.decode64(image))

    ActionDispatch::Http::UploadedFile.new(
      tempfile: tempfile,
      filename: filename,
      original_filename: filename
    )
  end

@deve1212
Copy link

not working

@salahuddin-rakib
Copy link

salahuddin-rakib commented Aug 13, 2022

It worked for me this way:
My gist link

def base64_to_file(base64_data, filename = 'image')
  return base64_data unless base64_data.present? && base64_data.is_a?(String)

  regex = /data:image\/([a-z]{3,4});base64,/
  type_fetch_regex = /\/(.*?);/
  start_text = regex.match(base64_data)
  type = base64_data[type_fetch_regex, 1]
  if start_text && type
    file = File.new("#{filename}.#{type}", 'wb')
    file.write(Base64.decode64(base64_data[start_text.to_s.length..-1]))
  else
    nil
  end
end

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