title: how to convert data URI to file in Ruby
body: <p>How do I convert a data URI that comes from the result of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader" rel="nofollow noreferrer">FileReader API</a> into an image file that can be saved in the file system in Ruby?</p>
  
  <p>What I'm currently trying to do is using base64 decode to convert the data_uri string which looks like this: <code>data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgA...</code> into base 64 encoded string because according to this <a href="https://stackoverflow.com/questions/6735414/php-data-uri-to-file">stackoverflow answer</a> I need to replace all the instances of spaces into <code>+</code>. 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:</p>
  
  <pre><code>src = data_uri.gsub! ' ', '+'
  src = Base64.decode64(src)
  f = File.new('uploads/' + 'sample.png', "w")
  f.write(src)
  f.close
  </code></pre>
  
  <p>I get the following error:</p>
  
  <pre><code>undefined method `unpack' for nil:NilClass
  </code></pre>
  
  <p>What I'm trying to achieve here is to be able to convert the data URI to a file.</p>