如何将 Base64 图像附加到 Active Storage 对象?

Ahm*_*lah 6 ruby base64 ruby-on-rails rails-activestorage ruby-on-rails-5.2

我可以从光盘附加一个 png 图像,一切正常:

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

String但是,当我保存 Base64 png 图像(通过以下方式编码为类似内容)时,它无法给出像太小的空方块这样的结果"data:image/png;base64,iVB**..REST OF DATA..**kSuQmCC"

obj.attachment.attach(
  io: StringIO.new(encoded_base_sixty_four_img),
  filename: "image_name",
  content_type: "image/png"
)
Run Code Online (Sandbox Code Playgroud)

我也尝试解码它但给出了相同的错误:

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"
)
Run Code Online (Sandbox Code Playgroud)

还尝试将此解码值写入File但没有任何效果,给出空白图像结果:

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

那么还有其他想法吗?

Ahm*_*lah 8

感谢@tadman,当我将其剥离时data:image/png;base64,,部分无法处理,Base64.decode64一切正常。