Skip to content

Instantly share code, notes, and snippets.

@simonqian
Created April 14, 2017 09:15
Show Gist options
  • Save simonqian/490302d44d401e7a27f45d200cb2b493 to your computer and use it in GitHub Desktop.
Save simonqian/490302d44d401e7a27f45d200cb2b493 to your computer and use it in GitHub Desktop.

Revisions

  1. simonqian created this gist Apr 14, 2017.
    28 changes: 28 additions & 0 deletions base64_to_file.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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