How to attach Base64 image to Active Storage object?

淺唱寂寞╮ 提交于 2020-04-17 17:54:53

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/61157933/how-to-attach-base64-image-to-active-storage-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!