Skip to content

Instantly share code, notes, and snippets.

@shrikanthkr
Last active September 6, 2019 16:21
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save shrikanthkr/10097999 to your computer and use it in GitHub Desktop.
Save shrikanthkr/10097999 to your computer and use it in GitHub Desktop.
Saving base64 string with Carrierwave

In the controller action

image_file = change_img_params(params[:avatar]) #params[:avatar] - base64 string

def change_img_params(img)
begin
  Base64.decode64(img) #To check if thats a base64 string
  if img
    img = file_decode(img.split(',')[1],"some file name") #getting only the string leaving out the data/<format>
  end
rescue Exception => e
  img #Returning if its not a base64 string
end
end

Helpers

def file_decode(base, filename)
    file = Tempfile.new([file_base_name(filename), file_extn_name(filename)])
    file.binmode
    file.write(Base64.decode64(base))
    file.close
    file
end

def file_base_name(file_name)
    File.basename(file_name, file_extn_name(file_name))
end

def file_extn_name(file_name)
    File.extname(file_name)
end
@pedrosfdcarneiro
Copy link

Thanks! 🍺

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