Module: AttachmentsHelper

Instance Method Summary collapse

Instance Method Details

#base64_attachments_to_files(base64_attachments) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/helpers/attachments_helper.rb', line 2

def base64_attachments_to_files(base64_attachments)
  base64_attachments.map do |base_64_attachment|
    next unless base_64_attachment =~ /^data:(.*?);base64,(.*)$/

    content_type = ::Regexp.last_match(1)
    base64_data = ::Regexp.last_match(2)
    decoded_data = Base64.decode64(base64_data)
    file_extension = content_type.split('/').last
    file_name = "#{SecureRandom.uuid}.#{file_extension}"

    temp_file = Tempfile.new([file_name, ".#{file_extension}"])
    temp_file.binmode
    temp_file.write(decoded_data)
    temp_file.rewind

    ActionDispatch::Http::UploadedFile.new(
      tempfile: temp_file,
      filename: file_name,
      type: content_type
    )
  end.compact
end

#base64_with_filename_to_files(base64_files) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/helpers/attachments_helper.rb', line 24

def base64_with_filename_to_files(base64_files)
  base64_files.map do |file_obj|
    next unless file_obj[:base64_file].present? && file_obj[:file_name].present?
    base64_data_uri = file_obj[:base64_file]

    # Match the base64 data URI
    next unless base64_data_uri =~ /^data:(.*?);base64,(.*)$/

    content_type = Regexp.last_match(1)
    base64_data = Regexp.last_match(2)
    decoded_data = Base64.decode64(base64_data)

    file_extension = content_type.split('/').last
    safe_file_name = file_obj[:file_name]

    # Create and write to Tempfile
    temp_file = Tempfile.new([SecureRandom.uuid, ".#{file_extension}"])
    temp_file.binmode
    temp_file.write(decoded_data)
    temp_file.rewind

    ActionDispatch::Http::UploadedFile.new(
      tempfile: temp_file,
      filename: safe_file_name,
      type: content_type
    )
  end.compact
end