How to convert data URI to file in Ruby

How to convert the data URI that is obtained from the result of the FileReader API into an image file that can be saved in a file in Ruby?

I am currently trying to use base64 decoding to convert a data_uri string that looks like this: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgA... into base 64 encoding, because according to this, https://stackoverflow.com/a/166146 121339 / ... I need to replace all instances of spaces with + . The answer is in PHP, but I'm working on Ruby and Sinatra right now, so I'm not sure if it still applies, but when using 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 the ability to convert data URIs to a file.

+8
ruby data-uri sinatra
source share
1 answer

No need to reinvent the wheel. Use data_uri gem.

 require 'data_uri' uri = URI::Data.new('data:image/gif;base64,...') File.write('uploads/file.jpg', uri.data) 
+12
source share

All Articles