How to attach Base64 image to Active Storage object?

Viewed 2472

I can attach a png image from disc by and everything works just fine:

obj.attachment.attach(
  io: File.open('dog.png'),
  filename: "image_name",
  content_type: "image/png"
)

But it doesn't work giving result like too tiny empty square when I save a Base64 png image which encoded into String something like that "data:image/png;base64,iVB**..REST OF DATA..**kSuQmCC" by:

obj.attachment.attach(
  io: StringIO.new(encoded_base_sixty_four_img),
  filename: "image_name",
  content_type: "image/png"
)

Also I tried to decoded it but gives the same error:

decoded_base_sixty_four_img = Base64.decode64(encoded_base_sixty_four_img)
obj.attachment.attach(
  io: StringIO.new(decoded_base_sixty_four_img),
  filename: "image_name",
  content_type: "image/png"
)

Also tried writing this decoded value into a File but nothing worked too giving blank image result:

file = file.write(decoded_base_sixty_four_img)
obj.attachment.attach(
  io: file,
  filename: "image_name",
  content_type: "image/png"
)

So any other thoughts?

2 Answers

Thanks to @tadman, data:image/png;base64, part can't be handled by Base64.decode64 when I stripped it off everything worked fine.

This worked for me.

          Model.create!(
            product: product,
            image: { 
              io: StringIO.new(Base64.decode64(params[:base_64_image].split(',')[1])),
              content_type: 'image/jpeg',
              filename: 'image.jpeg'
            }
          )
Related