How do I convert a data URI that comes from the result of the FileReader API into an image file that can be saved in the file system in Ruby?

What I'm currently trying to do is using base64 decode to convert the data_uri string which looks like this: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgA... into base 64 encoded string because according to this stackoverflow answer I need to replace all the instances of spaces into +. The answer is in PHP but I'm currently working on Ruby and Sinatra so I'm not sure if it still applies, but when using the equivalent code:

src = data_uri.gsub! ' ', '+'
src = Base64.decode64(src)
f = File.new('uploads/' + 'sample.png', "w")
f.write(src)
f.close

I get the following error:

undefined method `unpack' for nil:NilClass

What I'm trying to achieve here is to be able to convert the data URI to a file.

有帮助吗?

解决方案

There's no need to reinvent the wheel. Use the data_uri gem.

require 'data_uri'

uri = URI::Data.new('data:image/gif;base64,...')
File.write('uploads/file.jpg', uri.data)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top